我正在使用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)
即使我可以使用删除Python异常消息try
and except
,我还想要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
也许是这样的?
def shell(command):
try:
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
except Exception, e:
output = str(e.output)
finished = output.split('\n')
for line in finished:
print line
return
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)