In Python subprocess, what is the difference between using Popen() and check_output()?

佐手、 提交于 2021-02-05 08:08:50

问题


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

With Popen, this could be run with

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

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?


回答1:


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

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




回答2:


From the documentation:

check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code.



来源:https://stackoverflow.com/questions/39510029/in-python-subprocess-what-is-the-difference-between-using-popen-and-check-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!