python - 子进程 - Grep Broken Pipe

标签 python grep subprocess

此处为 Python 2.4.x。

一直在努力让子进程与 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:写入输出:损坏的管道”错误。

它必须是我所缺少的简单东西,我只是无法发现它。有什么想法吗?

提前谢谢你。

最佳答案

这里的问题是对于 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()

关于python - 子进程 - Grep Broken Pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839194/

相关文章:

python - python多处理中父进程全局变量如何复制到子进程

Python 子进程 stdin=subprocess.PIPE 和 unicode

Python 3.如何运行外部程序并执行命令?

python - 如何使用Python脚本在Linux上启动应用程序?

python - 艰难地学习 Python 示例 5

regex - 嵌套括号内的 grep

linux - grep 不作为正则表达式

python - 使用 Array 或 Series 从多列中进行选择

awk - 查找、替换和移动包含特定字符串的行

python - 用子进程替换 commands.getoutput