2011-03-30 109 views
3

調用subprocess.check_call()允許爲stdout指定一個文件對象,但是在將數據寫入文件之前,我想在逐行的基礎上修改它們。將subprocess.check_call的stdout重定向到函數?

我目前輸出重定向到一個臨時文件(由tempfile.TemporaryFile()創建。check_call結束後,我讀了臨時文件中的行由行,做了修改和寫入最終輸出文件。

由於輸出是大,一個純粹的內存解決方案是不可行的,我想修改的即時數據和寫入直接在最終輸出文件。

有誰知道如何做到這一點?

回答

2
def check_call_modify(command, modifier_function, output_file) 
    p = subprocess.Popen(command, stdout=subprocess.PIPE) 
    for line in p.stdout: 
     line = modifier_function(line) 
     output_file.write(line)  
    p.wait() 
    if p.returncode: 
     raise subprocess.CalledProcessError(p.returncode, command) 
    return p.returncode 

使用它傳遞一個函數來修改每一行和文件。阿呆下面的例子將在大寫節省ls -l的結果listupper.txt

with open('listupper.txt', 'w') as f: 
    check_call_modify(['ls', '-l'], operator.methodcaller('upper'), f) 
-1

Python是鴨類型的,所以你可以隨時將其傳遞給check_call之前包裝你的文件對象。

這個答案有一個doing it for write()的例子,但要徹底,你可能還想包裝writelines()

+0

-1:不,它不起作用,因爲子進程需要一個帶'.fileno()'方法的對象,並直接寫入由它返回的文件描述符。事實上,文件描述符直接傳遞給子進程,所以python不參與寫入。 – nosklo 2011-03-30 21:45:12

+0

奇數。我以爲我記得能夠在沒有'.fileno()'的情況下傳遞類似文件的對象。好吧。我猜,我的錯誤。 – ssokolow 2011-03-31 12:05:27

相關問題