简体   繁体   English

尽管在python子进程中提供了stderr = PIPE,但仍将输出抛出到外部

[英]Throws output outside, despite giving stderr=PIPE in python subprocess

    str = "blah -l"
    cpuinfo = subprocess.Popen(str.split(),stdout=PIPE,stderr=PIPE)

    tuples = cpuinfo.communicate()

In the above code, when I give str=[some_valid_command] gives the output to tuples. 在上面的代码中,当我给出str = [some_valid_command]时,将输出提供给元组。 When I give an invalid command, I expect the error to be taken to PIPE, but it is still throwing out on the console.... I am not quite sure, where I understood it wrong.... 当我发出无效命令时,我希望该错误将带给PIPE,但仍会在控制台上抛出该错误。...我不太确定,我在哪里理解错了...。

Thanks..... 谢谢.....

I'm not sure if you are seeing the stderr actually appear on the console, or are simply running into the Python failure to spawn a process named "blah", which is produced when running the example that you provided... 我不确定您是否看到stderr实际上出现在控制台上,还是只是在运行Python失败时才生成名为“ blah”的进程,该进程是在运行您提供的示例时产生的...

The output of the example would be Python raising an OSError: [Errno 2] No such file or directory , which is to be expected unless you have an executable script called "blah" in the PATH 该示例的输出将是Python引发OSError: [Errno 2] No such file or directory ,除非您在PATH中有一个名为“ blah”的可执行脚本,否则这是不希望的。

I did a simple test, and wrote a bash script like this: 我做了一个简单的测试,并编写了一个bash脚本,如下所示:

#!/bin/bash

echo "This is stdout"
echo "This is a failure on stderr" >&2
exit 1

After giving that script executable permissions, I repeated your example but instead called my script (named fail.sh in the local directory) as such: 在授予该脚本可执行文件权限之后,我重复了您的示例,但这样称呼我的脚本(在本地目录中名为fail.sh):

import subprocess

cmd = './fail.sh'
proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()

This returned ('This is stdout\\n', 'This is a failure on stderr\\n') as expected. 按预期返回此结果('This is stdout\\n', 'This is a failure on stderr\\n')

So perhaps what you're really seeing here is that whatever program you're trying to call (if it's not blah), simply doesn't exist on your PATH. 因此,也许您真正在这里看到的是您要调用的任何程序(如果不是这样的话)都根本不存在于PATH中。

Also a note on using str as a label in Python: str is a built-in type and should not be used as a name for a variable or function, unless you specifically want to "over-load" the built-in function. 还要注意在Python中使用str作为标签的注意事项: str是内置类型,不应用作变量或函数的名称,除非您特别想“重载”内置函数。 Same goes for string , which is a class. string也是一个类。

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

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