【问题标题】:In Python subprocess, what is the difference between using Popen() and check_output()?在 Python 子进程中,使用 Popen() 和 check_output() 有什么区别?
【发布时间】:2016-09-15 11:32:29
【问题描述】:

以shell命令“cat file.txt”为例。

使用 Popen,这可以运行

import subprocess
task = subprocess.Popen("cat file.txt", shell=True,  stdout=subprocess.PIPE)
data = task.stdout.read()

使用 check_output,可以运行

import subprocess
command=r"""cat file.log"""
output=subprocess.check_output(command, shell=True)

这些似乎是等价的。这两个命令的使用方式有什么区别?

【问题讨论】:

    标签: python bash shell subprocess


    【解决方案1】:

    Popen 是定义用于与外部进程交互的对象的类。 check_output() 只是 Popen 实例的包装器,用于检查其标准输出。这是 Python 2.7(无文档字符串)的定义:

    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
    

    (定义有很大不同,但最终仍然是Popen 实例的包装器。)

    【讨论】:

      【解决方案2】:

      来自the documentation

      如果被调用进程返回非零返回码,check_call()check_output() 将引发 CalledProcessError

      【讨论】:

        猜你喜欢
        • 2018-04-16
        • 2017-05-28
        • 2016-10-31
        • 2011-12-02
        • 1970-01-01
        • 2012-11-16
        • 2013-08-25
        • 2012-01-22
        相关资源
        最近更新 更多