2010-01-07 17 views
26

我需要使用標準UNIX diff命令創建diff文件,並使用python 子流程模塊。問題是我必須比較文件和流而不創建臨時文件。我想通過os.mkfifo方法使用命名管道,但沒有達到任何好的結果。請你能寫一個關於如何解決這個問題的簡單例子嗎?我試過像這樣:如何區分文件和輸出流「即時」?

fifo = 'pipe' 
os.mkfifo(fifo) 
op = popen('cat ', fifo) 
print >> open(fifo, 'w'), output 
os.unlink(fifo) 
proc = Popen(['diff', '-u', dumpfile], stdin=op, stdout=PIPE) 

但似乎diff沒有看到第二個參數。

回答

36

您可以使用「 - 」作爲diff的參數來表示stdin

+0

然後,你可以通過'標準輸入= PIPE'到'Popen'通話,然後'proc.stdin.write(data)'。 – LeafStorm 2010-01-07 18:14:42

8

你也許可以考慮使用difflib python模塊(我已經鏈接到這裏的一個例子),並創建一些直接生成並打印diff的東西,而不是依賴於diff。 difflib中的各種函數方法可以接收可以處理成各種類型差異的字符緩衝區。

或者,您可以構建一個管道和使用過程中替換像這樣

diff <(cat pipe) dumpfile # You compare the output of a process and a physical file without explicitly using a temporary file. 

有關詳細信息,請http://tldp.org/LDP/abs/html/process-sub.html