python - 如何在Python中通过管道执行命令?

标签 python pipe xargs

我使用 find 和 wc 使用管道获取总 LOC。

find . -name "*.cpp" -print | xargs wc

  44     109     896 ./main.cpp
 ...
 288    1015    8319 ./src/util/util.cpp
 733    2180   21494 total

我需要使用 python 自动获取 LOC,我将运行 find .. | xargs命令多次,获取结果并处理以获得总LOC。

如何在Python中通过管道执行命令? 我尝试了这个,但它什么也没返回。

import subprocess
p = subprocess.Popen(['find', '.', '-name', "*.cc", "-print", "|", "xargs", "wc"], 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE)
out, err = p.communicate()
print out

添加

有了 konishchev 的提示,我可以让它工作。

p1 = Popen(['find', '.', '-name', "*.cc", "-print"], stdout=PIPE)
p2 = Popen(["xargs", "wc"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
print output

最佳答案

您必须像描述的那样连接两个 Popen 对象 here .

但我想推荐psh module ,因为它更容易用于此类事情。

关于python - 如何在Python中通过管道执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221585/

相关文章:

bash - 使用 xargs 显示 git 别名中的命令

python - Raspberry Pi & Python 2.7 - 尝试打印给所有用户

python - Pandas DataFrame 按时间戳分组

python - 使用 PyScripter 执行带有参数的 python 文件

c - 在 C 中实现管道

node.js - 进程替换 - Node.js child_process

linux - 如何过滤流/管道以删除空部分的 header ?

linux - 我怎样才能在 linux 的命令中间用 xargs 传递所有参数

bash - 带有输入文件和输出文档的 Wget

python matplotlib 标签/标题错误字符