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'
どこが間違っているのかわからないことを認めます。