文章目录
外部链接
[1]subprocess
[2]python subprocess模块使用总结
subprocess
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
0,subprocess.run()
使用参数运行命令并返回完整的进程实例
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)
If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output.
result = subprocess.run(['ls' ,'/opt','-al'])
#print(resule):CompletedProcess(args=['ls', '/opt', '-al'], returncode=0)
**subprocess.PIPE:**可以为数据提供一个缓冲区,如果stdout输出在PIPE,则控制台上不会再次显示
返回的结果:class subprocess.CompletedProcess:
The return value from run(), representing a process that has finished.
args
The arguments used to launch the process. This may be a list or a string.
returncode
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.
A negative value -N indicates that the child was terminated by signal N (POSIX only).
stdout
Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stdout was not captured.
If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.
stderr
Captured stderr from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stderr was not captured.
check_returncode()
If returncode is non-zero, raise a CalledProcessError.
1,hight-level API
1.1,subprocess.call()
父进程等待子进程完成
返回退出信息(returncode,相当于Linux exit code)
1.2,subprocess.check_call()
父进程等待子进程完成
返回0
检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try…except…来检查
1.3,subprocess.check_output()
父进程等待子进程完成
返回子进程向标准输出的输出结果
检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查。
使用示例:
import subprocess
result = str(subprocess.check_output('ls /opt -al',shell=True).decode('utf-8'))
print(result)
shell=False(default)时,采用下面list的方式。如果在shell=True的情况下列表,默认只运行第一个元素,后面几个并不会读进去。
以下面为例,过为True则返回当前的目录信息,对ls来说参数并没有读进来
import subprocess
result = str(subprocess.check_output(['ls' ,'/opt','-al']).decode('utf-8'))
print(result)
4,subprocess.Popen()
上面3个函数都是基于Popen()的封装.
class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
数据的输入输出和CompletedProcess基本一致。