我使用subprocess
模块和check_output()
在Python脚本中创建了一个虚拟shell,它可以很好地处理返回零退出状态的命令,但是对于那些不返回零退出状态的命令,它会返回一个异常,而不会打印在普通shell的输出中显示的错误。
例如,我会期望一些东西像这样工作:
>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory
但实际情况是:
>>> shell('cat non-existing-file')
CalledProcessError: Command 'cat non-existing-file' returned non-zero exit status 1 (file "/usr/lib/python2.7/subprocess.py", line 544, in check_output)
尽管我可以使用try
和except
删除Python异常消息,但我仍然希望向用户显示cat: non-existing-file: No such file or directory
。
我该怎么做呢?shell()
:
def shell(command):
output = subprocess.check_output(command, shell=True)
finished = output.split('\n')
for line in finished:
print line
return
2条答案
按热度按时间rkue9o1l1#
像这样的吗?
agxfikkp2#
如果你使用的是Python 3.5+,你可以用
check=False
运行它:如果check为true,并且进程以非零退出代码退出,则将引发CalledProcessError异常。该异常的属性保存参数、退出代码以及stdout和stderr(如果它们被捕获)。
对于较旧的Python 3版本,检查调用和不检查调用的方法不同。
要获取输出,只需传递
capture_output=True
,然后从CompletedProcess
获取stdout
值