2013-03-26 99 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