2016-09-15 42 views
1

以shell命令「cat file.txt」爲例。在Python子流程中,使用Popen()和check_output()有什麼區別?

隨着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) 

這些似乎是等價的。關於如何使用這兩個命令有什麼區別?

回答

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一個實例的包裝)

1

the documentation

check_call()check_output()將提高CalledProcessError如果被叫返回非零返回碼。

相關問題