Python模块之 subprocess 具有可访问I/O流的子流程 子进程管理

模块作用简介:

subprocess - Subprocesses with accessible I/O streams
subprocess—具有可访问I/O流的子流程


官方 英文 帮助:https://docs.python.org/3/library/subprocess.html
官方 简体中文 帮助:https://docs.python.org/zh-cn/3/library/subprocess.html



必要操作:

>>> import subprocess 


安装:

>>> pip install subprocess
python 内置函数,无需安装


导入包:

>>> import subprocess


帮助查看:

>>> help(subprocess)

或 单独查看某个子方法(函数)

>>> help(Popen)


方法(函数):

>>> process = subprocess.Popen(command, shell=True, 
								executable='/bin/bash',
								stdin=subprocess.PIPE,
								stdout=subprocess.PIPE,
								stderr=subprocess.STDOUT,
								text=True)
>>> for line in iter(process.stdout.readline, ''):
            socketio.emit('compile_output', {'output': line})
        process.wait()


参数

class Popen 参数

参数 注释 备注
args shell命令,可以是字符串或者序列类型(如:list,元组)
bufsize 指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
executable 指定要执行命令的程序
stdin, stdout, stderr 分别表示程序的标准输入、输出、错误句柄
preexec_fn 只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
close_sfs 在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
shell 同上
cwd 设置指定子进程的当前目录
env 用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
universal_newlines 不同系统的换行符不同,True -> 同意使用 \n
startupinfo 只在windows下有效,将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
createionflags 同上


返回值

返回True,否则返回False。



使用示例:

示例1:

>>> 


示例2:

>>> 







相关文章:
Python安装包下载:https://www.cnblogs.com/wutou/p/17709685.html
Pip 源设置:https://www.cnblogs.com/wutou/p/17531296.html
pip 安装指定版本模块:https://www.cnblogs.com/wutou/p/17716203.html
【汇总】Python模块 - 总目录 https://www.cnblogs.com/wutou/p/15610071.html





参考、来源:
https://www.cnblogs.com/zhming26/p/6283361.html







posted @ 2025-09-08 22:19  悟透  阅读(30)  评论(0)    收藏  举报