【问题标题】:Python process pipes with subprocess.Popen带有 subprocess.Popen 的 Python 进程管道
【发布时间】:2016-05-20 12:54:15
【问题描述】:

这是一个测试文件:

gunzip -c file_1.gz
Line 1
Line 2
Line 3

我正在以这种方式执行 bash 命令:

cmd = "gunzip -c file_1.gz | grep 3"
subprocess.call(cmd, shell=True))
Line 3

我需要在多个文件上并行运行此命令,然后加入进程。所以看来我必须使用subprocess.Popen().communicate()。但是Popen 无法正确识别管道并将其提供给第一个命令,在我的例子中是 gunzip:

subprocess.Popen(cmd.split()).communicate())
gunzip: can't stat: | (|.gz): No such file or directory
gunzip: can't stat: grep (grep.gz): No such file or directory
gunzip: can't stat: 8 (8.gz): No such file or directory

我想保留整个命令并避免以这种方式分离它:

gunzip = subprocess.Popen('gunzip -c file_1.gz'.split(), stdout=subprocess.PIPE)
grep = subprocess.Popen('grep 3'.split(), stdin=gunzip.stdout, stdout=subprocess.PIPE)
gunzip.stdout.close()
output = grep.communicate()[0]
gunzip.wait()

有没有办法不分离命令并正确处理管道?

【问题讨论】:

  • “加入进程”是什么意思?您想捕获同时运行的多个进程的输出吗?这是code example。不相关:您的代码可能是 IO 绑定的,即,可能没有必要并行读取文件,除非它们已经在内存中。
  • 抱歉耽搁了。通过加入进程,我的意思是等到每个文件上的所有 grep 都完成。您所指的答案值得注意!

标签: python-2.7 pipe subprocess


【解决方案1】:

要运行grep 3 命令,您需要上一个命令的输出,因此无法使用 subprocess.Popen 在单个命令中成功运行此命令。

如果你总是想对所有文件运行grep 3,你可以加入所有gunzip -c file_x.gz的结果,然后在整个列表中只运行一次grep命令。

subprocess.Popen('gunzip -c file_1.gz'.split(), stdout=subprocess.PIPE)
subprocess.Popen('gunzip -c file_2.gz'.split(), stdout=subprocess.PIPE)
...
grep = subprocess.Popen('grep 3'.split(), stdin=all_gunzip_stdout, stdout=subprocess.PIPE)

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 2019-12-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2012-03-21
    • 2017-03-10
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多