What exactly means that the stdout (or stdin) is set to subprocess.PIPE in Popen?

Viewed 984

I have already read the documentation about subprocesses in python, but still cannot quite understand this.

When using Popen, and we set the parameter stdout (or stdin) to subprocesses.PIPE, what does that actually mean?

The documentation says

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively... PIPE indicates that a new pipe to the child should be created.

what does this mean?

For example, if I have two subprocesses both with stdout to PIPE, are the ouptuts mixed? (I don't think so)

more importantly, if I have a subprocess with stdout set to PIPE and later another subprocess with stdin set to PIPE , is that pipe the same, the output of one goes to the other?

Can someone explain me that part of the documentation that seems criptic to me?


Additional notes: For example

import os
import signal
import subprocess
import time

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen("sar -u 1 > mylog.log", stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

// Here another subprocess
subprocess.Popen(some_command, stdin=subprocess.PIPE)
time.sleep(10)

os.killpg(os.getpgid(pro.pid), signal.SIGTERM) 

Does the output of sar goes as input to "some command"?

1 Answers

Please see the document.

So as you can see, the PIPE is a special value, it "indicates that a new pipe to the child should be created." Which means, stdout=subprocess.PIPE and stderr=subprocess.PIPE results in two different pipes.

And for your example, the answer is no. These are two different pipes.

Actually you can print out the subprocess.PIPE:

print(subprocess.PIPE)
# -1
print(type(subprocess.PIPE))
# int
# So it is just an integer to represent a special case.
Related