2012-05-31 106 views
1

Python 2.4.x這裏。Subprocess - Grep Broken Pipe

一直試圖讓子進程與glob一起工作。

嗯,這是問題區域。

def runCommands(thecust, thedevice): 
    thepath='/smithy/%s/%s' % (thecust,thedevice) 
    thefiles=glob.glob(thepath + '/*.smithy.xml') 
    p1=subprocess.Popen(["grep", "<record>"] + thefiles, stdout=subprocess.PIPE) 
    p2=subprocess.Popen(['wc -l'], stdin=p1.stdout, stdout=subprocess.PIPE) 
    p1.stdout.close() 
    thecount=p2.communicate()[0] 
    p1.wait() 

我在屏幕上收到大量的「grep:writing output:Broken pipe」錯誤。

這是一些簡單的東西我錯過了,我只是不能發現它。任何想法?

預先感謝您。

+0

有一對夫婦身邊子塔(非常漂亮)的包裝會使你的生活更容易像[PBS](https://github.com/amoffat/pbs很多)和[plumbum](https://github.com/tomerfiliba/plumbum)。 –

+0

那些看起來非常酷 - 不幸的是,我不是在一個環境中,我可以在2.4的模塊之外添加模塊 – Chasester

回答

5

這裏的問題是,對於p2您的參數列表應該是['wc', '-l']而不是['wc -l']

目前,它正在尋找一個名爲'wc -l'運行一個可執行文件,並沒有找到它,所以p2立即失敗並沒有什麼連接到p1.stdout,這會導致破裂的管道失誤。

試試下面的代碼:

def runCommands(thecust, thedevice): 
    thepath='/smithy/%s/%s' % (thecust,thedevice) 
    thefiles=glob.glob(thepath + '/*.smithy.xml') 
    p1=subprocess.Popen(["grep", "<record>"] + thefiles, stdout=subprocess.PIPE) 
    p2=subprocess.Popen(['wc', '-l'], stdin=p1.stdout, stdout=subprocess.PIPE) 
    p1.stdout.close() 
    thecount=p2.communicate()[0] 
    p1.wait() 
+0

啊,大聲哭泣。是的,它做到了。 謝謝! – Chasester

0

這似乎是因爲您在grep完成輸出之前正在關閉p1.stdout。也許你打算關閉pt.stdin?似乎沒有任何理由要關閉其中任何一個,所以我只是刪除p1.stdout.close()聲明。

+0

沒有運氣,刪除close()語句相同的錯誤後。 – Chasester

+0

看看文檔:http://docs.python.org/library/subprocess.html#replacing-shell-pipeline - 它看起來對我來說是正確的。 – mgilson

相關問題