Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python子流程中,使用Popen()和check_output()有什么区别?_Python_Bash_Shell_Subprocess - Fatal编程技术网

在Python子流程中,使用Popen()和check_output()有什么区别?

在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

以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_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