shell 忽略CalledProcessError

dwbf0jvd  于 2023-06-24  发布在  Shell
关注(0)|答案(2)|浏览(122)

我使用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 or directory
我该怎么做呢?
shell()

def shell(command):
    output   = subprocess.check_output(command, shell=True)
    finished = output.split('\n')

    for line in finished:
      print line
    return
rkue9o1l

rkue9o1l1#

像这样的吗?

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
agxfikkp

agxfikkp2#

如果你使用的是Python 3.5+,你可以用check=False运行它:

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

如果check为true,并且进程以非零退出代码退出,则将引发CalledProcessError异常。该异常的属性保存参数、退出代码以及stdout和stderr(如果它们被捕获)。
对于较旧的Python 3版本,检查调用和不检查调用的方法不同。
要获取输出,只需传递capture_output=True,然后从CompletedProcess获取stdout

相关问题