简体   繁体   中英

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

You are comparing apples and oranges. The contents of sys.stdin are str instances (though you can configure it to return bytes , somewhat painstakingly; subprocess on Python 3.x returns bytes unless you specify text=True or similar to decode those bytes into a str ).

Python 3.7.2 (default, Jan 29 2019, 13:41:02) 
[Clang 10.0.0 (clang-1000.10.44.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> type(sys.stdin)
<class '_io.TextIOWrapper'>
>>> line = sys.stdin.readline()
fnord
>>> type(line)
<class 'str'>
>>> import subprocess
>>> s = subprocess.run(['true'], capture_output=True, text=True)
>>> type(s)
<class 'subprocess.CompletedProcess'>
>>> type(s.stdout)
<class 'str'>

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.

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