2010-09-06 21 views
3

我有以下代碼:發送大文件到管道輸入在python

sourcefile = open(filein, "r") 
targetfile = open(pathout, "w") 

content= sourcefile.read(): 

p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) 
p.communicate(content) 

sourcefile.close() 
targetfile.close() 

中的資源文件中的數據是相當大的,所以它需要內存/交換了很多將其存儲在「內容」。我試圖直接將文件發送到標準輸入stdin = sourcefile,除了外部腳本「掛起」,即:不斷等待EOF。這可能是外部腳本中的一個錯誤,但目前我無法控制。

有關如何將大文件發送到我的外部腳本的任何建議?

+0

如果直接提供文件描述符,外部腳本會掛起,這很奇怪。當它從終端運行時,它是否也會掛起:'腳本< infile > outfile'? – rkhayrov 2010-09-06 12:45:12

回答

4

p.communicate(content)替換爲從sourcefile讀取的循環,並以塊的形式寫入p.stdin。當sourcefile是EOF時,請務必關閉p.stdin

sourcefile = open(filein, "r") 
targetfile = open(pathout, "w") 

p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) 
while True: 
    data = sourcefile.read(1024) 
    if len(data) == 0: 
     break 
    p.stdin.write(data) 
sourcefile.close() 
p.stdin.close() 

p.wait() 
targetfile.close() 
+0

這很好,謝謝! – Oli 2010-09-06 13:14:12