2013-03-26 46 views
-2

我注意到这种奇怪的行为在python-我试图记录一个进程的输出,然后读取这个输出,并对它做一些处理。即使该文件在程序运行后打开时也具有所有文本,但我无法读取任何内容。奇怪的IO行为与子进程

它的那样简单

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,一切都在那里。任何暗示我可能做错了什么?从“等待过程到完成”我没有得到任何印刷品,但该过程需要一秒左右的时间才能完成。

+0

什么是'f'?不应该是'f = open(...'? – Blender 2013-03-26 00:04:15

+0

对不起,错字,修正。这不是我的程序中的问题。 – Illusionist 2013-03-26 00:04:50

+2

@Illusionist有很多地方需要显示这不是程序你正在运行,请尽可能少地修改[* actual * program](http://sscce.org/),否则错误可能在其他地方。例如,[此演示程序](https ://gist.github.com/phihag/5242061)在我的系统上工作正常 – phihag 2013-03-26 00:10:08

回答

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()是什么打算但是没有。问题是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关键字,以确保该文件始终正确完成它的任务后关闭。

+0

非常感谢!! – Illusionist 2013-03-26 01:31:32

+0

一个[with](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)-statement会在套件完成后自动关闭你的文件,所以'w.close( )'和'f.close()'没有必要 – ferkulat 2013-05-22 14:36:13

+0

@ferkulat啊,忘记编辑它时粘贴他的代码。 ;) – eandersson 2013-05-22 17:08:30

4

等待,直到你的转储过程完成:

​​

发生的事情是,因为你的等待循环是错误的,你不给的过程中改变投票之前启动,因此不会就迫不及待地连在关闭/打开文件之前启动:

+0

+1好的,但是除非我误解他,否则他提到文件确实包含了所有期望的文本,它只是在第二部分没有出现。 – eandersson 2013-03-26 00:23:38

+0

是的,但它执行阅读开放位 – perreal 2013-03-26 00:24:16

+1

顺便填充他的代码的问题,否则是一个错字。while循环应该是'None',而不是'None'。 – eandersson 2013-03-26 00:28:56