gpt4 book ai didi

python - 忽略 CalledProcessError

转载 作者:太空狗 更新时间:2023-10-29 17:48:40 24 4
gpt4 key购买 nike

我正在使用 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)

即使我可以使用 tryexcept 删除 Python 异常消息,我仍然想要 cat: non-existing-file: No such file 或者显示给用户的目录

我该怎么做?

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

关于python - 忽略 CalledProcessError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com