【问题标题】:Redirecting stderr to stdout in subprocess.check_output does not print out the error message. Why?在 subprocess.check_output 中将 stderr 重定向到 stdout 不会打印出错误消息。为什么?
【发布时间】:2019-10-18 08:06:08
【问题描述】:

我正在使用 check_output 从 python 的子进程模块调用 shell 命令。

如下图,我尝试通过将stderr重定向到stdout来得到执行错误shell命令lsl -l的错误信息。但它显然不起作用。为什么?

In [5]: subprocess.check_output("lsl -l", shell=True,stderr=subprocess.STDOUT)                                             
---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-5-8dd15c76eb0f> in <module>
----> 1 subprocess.check_output("lsl -l", shell=True,stderr=subprocess.STDOUT)

/usr/lib/python3.5/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    624 
    625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 626                **kwargs).stdout
    627 
    628 

/usr/lib/python3.5/subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    706         if check and retcode:
    707             raise CalledProcessError(retcode, process.args,
--> 708                                      output=stdout, stderr=stderr)
    709     return CompletedProcess(process.args, retcode, stdout, stderr)
    710 

CalledProcessError: Command 'lsl -l' returned non-zero exit status 127

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    您应该尝试在命令后使用 ;exit 0;。 check_output 本身的文档说,如果进程以非零状态退出,它会引发 CalledProcessError。有关详细信息,请参阅check_output。试试下面的命令:

    subprocess.check_output("lsl -l;exit 0;", shell=True,stderr=subprocess.STDOUT)
    

    【讨论】:

    • 谢谢。但这对我来说似乎不是一个强大的解决方案。使用“exit 0”,甚至不会知道命令失败(除非要手动读取错误消息)。
    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多