简体   繁体   中英

Handling stdin and stdout

I'm trying to use subprocess to handle streams. I need to write data to the stream, and be able to read from it asynchronously (before the program dies, because mine's will take minutes to complete, however it products output).

For the learn case, I've been using the timeout command from Windows 7:

import subprocess
import time

args = ['timeout', '5']
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
p.stdin.write('\n') # this is supposed to mimic Enter button pressed event.

while True:
    print p.stdout.read() # expected this to print output interactively. This actually hungs.
    time.sleep(1)

Where am I wrong?

This line:

print p.stdout.read() # expected this to print output interactively. This actually hungs.

hangs because read() means "read all data until EOF". See the documentation . It seems like you may have wanted to read a line at a time:

print p.stdout.readline()

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