user3427070
user3427070

Reputation: 549

In subprocess.Popen, what's the difference between passing stdin=None and stdin=sys.stdin?

What would be difference between the below two commands? And would it vary by platform (e.g. Windows or Linux)?

Note: I believe this question applies equally for each of the keyword arguments stdin, stdout, and stderr.

A:

subprocess.Popen(some_command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)

B:

subprocess.Popen(some_command)

(Assuming we have subprocess and sys imported.)

The docs at https://docs.python.org/3/library/subprocess.html say:

With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.

Based on that, for stdin, it sounds like sys.stdin would give the child process the same file handle as the parent, which sounds the same as what the docs describe for None.

Upvotes: 1

Views: 329

Answers (1)

chepner
chepner

Reputation: 532093

sys.stdin isn't precisely the standard input of the current Python process, as you can assign a new file handle to it. Its value is initialized with the process's standard input, though. Child processes will inherit the original standard input, preserved in sys.__stdin__. An example:

import sys
import subprocess

with open("foo.txt") as f:
    sys.stdin = f
    subprocess.call(["cat"])

If you run this with an appropriate set of files:

$ echo hi > foo.txt
$ echo bye > bar.txt
$ python tmp.py < bar.txt
bye

then the output will be bye, not hi.

Upvotes: 2

Related Questions