在Python子进程中,使用Popen()和check_output()有什么区别? [英] In Python subprocess, what is the difference between using Popen() and check_output()?

查看:39
本文介绍了在Python子进程中,使用Popen()和check_output()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以shell命令"cat file.txt"为例.

Take the shell command "cat file.txt" as an example.

使用Popen,可以通过以下方式运行

With Popen, this could be run with

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

使用check_output,可以运行

With check_output, one could run

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

这些似乎是等效的.这两个命令的使用方式有何不同?

These appears to be equivalent. What is the difference with regards to how these two commands would be used?

推荐答案

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

Popen is the class that defines an object used to interact with an external process. check_output() is just a wrapper around an instance of Popen to examine its standard output. Here's the definition from Python 2.7 (sans docstring):

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 实例的包装.)

(The definition is quite a bit different, but is still ultimately a wrapper around an instance of Popen.)

这篇关于在Python子进程中,使用Popen()和check_output()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆