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

2023-12-11

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

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


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.)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python子进程中,使用Popen()和check_output()有什么区别? 的相关文章

随机推荐