Search code examples
pythontypessubprocessstdoutstdin

Python sys.stdin and subprocess stdout difference


I currently have a larger problem at hand so I started by trying to match the smaller differences to see if that'll fix my issue.

In my program, I was using a pipe and iterating through that input through sys.stdin. I noticed it's type is <class '_io.TextIOWrapper'>. I'm trying to avoid using a pipe and replaced my code to use subprocess.run() instead and noticed that the result has the type <class 'str'> instead.

This could be a really stupid question but I'm wondering why they're different and if I can get the subprocess stdout to be the same type as sys.stdin.

Using Python 3.7.5


Solution

  • subprocess.run returns a CompletedProcess instance, with the collected stdout/stderr captured all at once.

    If you want a stream, create a Popen instance, which will have stdout and stderr attributes that act like sys.stdin, and a stdin attribute that acts like sys.stdout. But beware pipe buffering/deadlock problems if you do anything fancy.