忽略 CalledProcessError [英] Ignoring CalledProcessError
问题描述
我正在使用 subprocess
模块和 check_output()
在我的 Python 脚本中创建一个虚拟 shell,它适用于返回零退出状态的命令,然而,对于那些不返回异常的人,它不会打印在普通 shell 的输出中显示的错误.
例如,我希望有这样的工作:
<预><代码>>>>shell('cat 不存在的文件')cat: non-existing-file: 没有那个文件或目录但是,这种情况发生了:
<预><代码>>>>shell('cat 不存在的文件')CalledProcessError:命令cat non-existing-file"返回非零退出状态 1(文件/usr/lib/python2.7/subprocess.py",第 544 行,在 check_output 中)即使我可以使用 try
和 except
删除 Python 异常消息,我仍然想要 cat: non-existing-file: No such file 或目录
显示给用户.
我该怎么做?
shell()
:
def shell(命令):输出 = subprocess.check_output(命令,shell=True)完成 = output.split('\n')对于线完成:印刷线返回
可能是这样的?
def shell(命令):尝试:输出 = subprocess.check_output(命令,shell=True,stderr=subprocess.STDOUT)除了例外,e:输出 = str(e.output)完成 = output.split('\n')对于完成的行:印刷线返回
I am using the subprocess
module and check_output()
to create a virtual shell in my Python script, and it works fine for commands that return a zero exit status, however for ones that don't it returns an exception without printing the error that would have been displayed in the output on a normal shell.
For instance, I would expect something to work like this:
>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory
But instead, this happens:
>>> 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)
Even though I could remove the Python exception message using try
and except
, I still want the cat: non-existing-file: No such file or directory
to display to the user.
How would I go about doing this?
shell()
:
def shell(command):
output = subprocess.check_output(command, shell=True)
finished = output.split('\n')
for line in finished:
print line
return
Something like this perhaps?
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
这篇关于忽略 CalledProcessError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!