2010-05-14 21 views
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但不會改變任何東西。

+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

回答

2

好吧,它似乎是在Python中的錯誤:http://bugs.python.org/issue3907

如果我更換線

for l in tun.stdout: 

通過

while True: 
    l = tun.stdout.readline() 

然後它正是我想要的方式。

相關問題