簡體   English   中英

處理stdin和stdout

[英]Handling stdin and stdout

我正在嘗試使用subprocess來處理流。 我需要將數據寫入流,並能夠異步讀取(在程序死亡之前,因為我的將需要幾分鍾才能完成,但產品輸出)。

對於學習案例,我一直在使用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)

我哪里錯了?

這一行:

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

掛起因為read()表示“讀取所有數據直到EOF”。 請參閱文檔 看起來你可能想要一次讀一行:

print p.stdout.readline()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM