【问题标题】:Ignoring CalledProcessError忽略 CalledProcessError
【发布时间】:2012-08-14 11:46:54
【问题描述】:

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

【问题讨论】:

    标签: python shell subprocess


    【解决方案1】:

    大概是这样的吧?

    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
    

    【讨论】:

    • 如何将 Popen 对象转换为字符串?它不适用于str()<subprocess.Popen object at 0x12a4f90>
    • 您可以使用 __str__() 方法。例如 output.__str__()
    • 好吧,现在它给出的输出是Command 'cat nope' returned non-zero exit status 1,我想要的是 shell 给出的错误而不是 Python 异常消息。
    • python 3,我将异常捕获代码替换为:“除了 subprocess.CalledProcessError as e:”,它可以工作
    • 子进程中应该有一个选项可以忽略这样的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多