在Python子流程中,使用Popen()和check_output()有什么区别?
以shell命令“cat file.txt”为例 有了Popen,就可以用在Python子流程中,使用Popen()和check_output()有什么区别?,python,bash,shell,subprocess,Python,Bash,Shell,Subprocess,以shell命令“cat file.txt”为例 有了Popen,就可以用 import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() 使用check_输出,可以运行 import subprocess command=r"""cat file.log""" output=subprocess.check_outp
import subprocess
task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE)
data = task.stdout.read()
使用check_输出,可以运行
import subprocess
command=r"""cat file.log"""
output=subprocess.check_output(command, shell=True)
这些似乎是等效的。这两个命令的使用方式有什么不同 来自:
check\u call()
和check\u output()
将在被调用进程返回非零返回代码时引发被调用进程错误
Popen
是定义用于与外部进程交互的对象的类check_output()
只是对Popen
实例的包装,用于检查其标准输出。以下是Python 2.7(sans docstring)中的定义:
(定义有点不同,但最终仍是Popen
实例的包装器)
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output