我想stdout
在python(3)脚本中捕获shell命令的流,同时能够检查shell命令的返回码是否返回错误(也就是说,如果它的返回码是不是 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.
尽管如此,当它失败时,我没有成功从shell命令获取返回码。我的代码如下所示:
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'
我承认我不知道我错在哪里。