2012-05-31 160 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

相关问题