简体   繁体   English

在 subprocess.check_output 中将 stderr 重定向到 stdout 不会打印出错误消息。 为什么?

[英]Redirecting stderr to stdout in subprocess.check_output does not print out the error message. Why?

I am calling a shell command from python's subprocess module, using check_output.我正在使用 check_output 从 python 的子进程模块调用 shell 命令。

As shown below, I try to get the error message of executing a wrong shell command lsl -l , by redirecting stderr to stdout.如下所示,我尝试通过将 stderr 重定向到 stdout 来获取执行错误 shell 命令lsl -l的错误消息。 But it does not work apparently.但它显然不起作用。 Why?为什么?

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

You should try using ;exit 0;您应该尝试使用;exit 0; after your command.在你的命令之后。 Documentation for check_output itself says that it raises CalledProcessError if the process exits with Non zero status. check_output 本身的文档说,如果进程以非零状态退出,它会引发CalledProcessError Refer check_output for more details.有关详细信息,请参阅check_output Try the below command:试试下面的命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM