2
我有代碼:Python subprocess.Popen掛在'for l在p.stdout'直到p終止,爲什麼?
#!/usr/bin/python -u
localport = 9876
import sys, re, os
from subprocess import *
tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT)
print "** Started tunnel, waiting to be ready ..."
for l in tun.stdout:
sys.stdout.write(l)
if re.search("Waiting for connection", l):
print "** Ready for SSH !"
break
的「./newtunnel」不會退出,它就會不斷地輸出越來越多的數據到標準輸出。但是,該代碼不會給出任何輸出,只是在tun.stdout中等待。
當我從外部終止newtunnel進程時,它將所有數據刷新到tun.stdout。所以看起來我在tun.stdout仍然運行時無法獲取任何數據。
這是爲什麼?我如何獲取信息?
請注意,Popen的默認bufsize爲0(無緩衝)。我也可以指定bufsize = 0但不會改變任何東西。
http://stackoverflow.com/questions/874815/how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5的潛在副本 – eswald 2010-05-14 22:41:19