我使用 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/