【发布时间】:2013-03-15 15:45:58
【问题描述】:
我在 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 时,一切都在那里。关于我可能做错了什么的任何提示?我根本没有从“等待过程完成”中得到任何打印,但该过程大约需要一秒钟才能运行。
【问题讨论】:
-
什么是
f?不应该是f = open(...吗? -
对不起,错字。固定的。这不是我程序中的问题。
-
@Illusionist 有很多地方很明显这不是您正在运行的程序。请发布actual program 并尽可能少修改 - 否则,错误可能在其他地方。例如,this demo program 在我的系统上运行良好。
-
最小化您的应用程序,但确保它仍然会重现问题。发布它。
-
你几乎不想像那样循环
poll。如果您想阻止直到完成,只需致电wait。如果你真的因为某种原因必须忙着等待,至少sleep每次通过循环,而不是试图消耗尽可能多的 CPU 时间,你可以什么都不做。
标签: python subprocess stdout