25

Python (3) スクリプトでシェル コマンドのストリームをキャプチャするstdoutと同時に、シェル コマンドがエラーを返した場合 (つまり、そのリターン コードが0 ではない)。

subprocess.check_outputこれを行うには適切な方法のようです。subprocessのマニュアルページから:

check_output(*popenargs, **kwargs)
    Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

それでも、シェルコマンドが失敗したときにリターンコードを取得することに成功しません。私のコードは次のようになります。

import subprocess
failing_command=['ls', 'non_existent_dir']

try:
    subprocess.check_output(failing_command)
except:
    ret = subprocess.CalledProcessError.returncode  # <- this seems to be wrong
    if ret in (1, 2):
        print("the command failed")
    elif ret in (3, 4, 5):
        print("the command failed very much")

このコードは、例外自体の処理で例外を発生させます。

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
AttributeError: type object 'CalledProcessError' has no attribute 'returncode'

どこが間違っているのかわからないことを認めます。

4

2 に答える 2

42

プロセス出力と返されたコードの両方を取得するには、次のようにします。

from subprocess import Popen, PIPE

p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)

subprocess.CalledProcessErrorクラスです。アクセスreturncodeするには、例外インスタンスを使用します。

from subprocess import CalledProcessError, check_output

try:
    output = check_output(["ls", "non existent"])
    returncode = 0
except CalledProcessError as e:
    output = e.output
    returncode = e.returncode

print(returncode)
于 2013-03-09T22:33:16.727 に答える
5

おそらく私の答えはもはや関連性がありませんが、次のコードで解決できると思います:

import subprocess
failing_command='ls non_existent_dir'

try:
    subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    ret =   e.returncode 
    if ret in (1, 2):
        print("the command failed")
    elif ret in (3, 4, 5):
        print("the command failed very much")
于 2014-02-26T12:56:05.287 に答える