简体   繁体   中英

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. 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....

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...

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

I did a simple test, and wrote a bash script like this:

#!/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:

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.

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.

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. Same goes for string , which is a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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