mic*_*yer 22 python subprocess python-3.x
我想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.
Run Code Online (Sandbox Code Playgroud)
但是,当它失败时,我没有成功从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")
Run Code Online (Sandbox Code Playgroud)
此代码在处理异常本身时引发异常:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: type object 'CalledProcessError' has no attribute 'returncode'
Run Code Online (Sandbox Code Playgroud)
我承认我不知道我哪里错了.
jfs*_*jfs 38
要获取进程输出和返回的代码:
from subprocess import Popen, PIPE
p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
很可能我的答案不再相关,但我认为可以通过以下代码解决:
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")
Run Code Online (Sandbox Code Playgroud)