2016-09-15 5 views
1

シェルコマンド "cat file.txt"を例に取ってください。 popenのでPythonのサブプロセスでは、Popen()とcheck_output()の使用の違いは何ですか?

これはcheck_outputで

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

で実行することができ、一つは、これらが表示されますが、同等であることを

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

を実行することができます。これらの2つのコマンドがどのように使用されるのかの違いは何ですか? the documentationから

答えて

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

:と呼ばれるプロセスは、ゼロ以外の戻りコードを返す場合

check_call()check_output()CalledProcessErrorが発生します。

関連する問題