忽略 CalledProcessError

问题描述 投票:0回答:3

我正在使用

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
python shell subprocess
3个回答
21
投票

也许是这样的?

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

3
投票

如果您使用的是 Python 3.5+,则可以使用

check=False
:

运行它
subprocess.run("exit 1", shell=True, check=False)

如果检查为 true,并且进程以非零退出代码退出,则会引发 CalledProcessError 异常。该异常的属性包含参数、退出代码以及 stdout 和 stderr(如果捕获了它们)。

对于较旧的 Python 3 版本,有不同的方法来检查和不检查调用。

要获取输出,只需传递

capture_output=True
,然后从
stdout
 获取 
CompletedProcess


0
投票

使用怎么样

subprocess.run()

import subprocess
output = subprocess.run(['cat', 'non-existing-file'], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
print (output.stderr.decode())

这是输出

> python3 file.py
cat: non-existing-file: No such file or directory
© www.soinside.com 2019 - 2024. All rights reserved.