简体   繁体   English

处理stdin和stdout

[英]Handling stdin and stdout

I'm trying to use subprocess to handle streams. 我正在尝试使用subprocess来处理流。 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: 对于学习案例,我一直在使用Windows 7中的timeout命令:

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". 挂起因为read()表示“读取所有数据直到EOF”。 See the documentation . 请参阅文档 It seems like you may have wanted to read a line at a time: 看起来你可能想要一次读一行:

print p.stdout.readline()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM