子进程的奇怪IO行为

时间:2013-03-26 00:02:41

标签: python subprocess stdout

我注意到python中这种奇怪的行为 - 我正在尝试记录进程的输出,然后读取此输出并对其进行一些处理。即使文件在程序运行后打开它时包含所有文本,我也无法读取任何内容。

就像

一样简单
f=open("blah.txt",'w')
#I log the output of a program with subprocess
Cmdline="program.exe"
Dump= subprocess.Popen(CmdLine,stdout=f,stderr=subprocess.STDOUT)
#Waiting for it to finish
while(Dump.poll() is not None): #returns None while subprocess is running
        print "waiting on process to finish \n"
f.flush() #I flush everything to make sure it was written
sys.stdout.flush()
f.close()
#now i need to read from this file

f= open("blah.txt", 'r')
line=f.readline()
while line:
    print line
    line=f.readline()

f.close()

我什么都没读,但是当我在运行程序后打开文件blah.txt时,一切都在那里。关于我可能做错的任何提示?我没有得到任何印刷品,等待过程完成"但这个过程大约需要一秒钟才能运行。

2 个答案:

答案 0 :(得分:4)

等到转储过程完成:

Dump= subprocess.Popen(CmdLine,stdout=f,stderr=subprocess.STDOUT)
#Waiting for it to finish
Dump.wait() # or -> while(Dump.poll() is None): print...

会发生什么情况,因为您的等待循环错误,您不会在轮询之前给进程一个更改以启动,因此它不会在关闭/打开文件之前等待它甚至启动:

答案 1 :(得分:1)

代码中的错误是这部分

while(Dump.poll() is not None): # While dump.pool is not None keep the loop going

应该是

while(Dump.poll() is None): # While dump.pool is None keep the loop going

在你的while循环中,只要Dump.poll()为None,就基本上保持循环。问题是Dump.pool()在流程完成之前返回None。这意味着while循环将立即被取消,然后才能捕获进程的任何输出。

这是我确认的代码的更新版本。

with open("blah.txt",'w') as w:
    #I log the output of a program with subprocess
    Cmdline="program.exe"
    Dump = subprocess.Popen(CmdLine,stdout=w,stderr=subprocess.STDOUT)
    #Waiting for it to finish
    while(Dump.poll() is None): #returns None while subprocess is running
        print "waiting on process to finish \n"
    w.flush() #I flush everything to make sure it was written
    sys.stdout.flush()

#now i need to read from this file
with open("blah.txt", 'r') as f:
    line=f.readline()
    while line:
        print line
        line=f.readline()

我还建议您使用with关键字确保文件在完成任务后始终正确关闭。