如何在Python中通过管道执行命令?
我使用find和wc获得使用管道的总LOC如何在Python中通过管道执行命令?,python,pipe,xargs,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,我将运行查找xargs命令多次,获取结果并处理以获取总LOC 如何在Python中通过管道执行命令? 我试过了,但没有结果 im
find . -name "*.cpp" -print | xargs wc
44 109 896 ./main.cpp
...
288 1015 8319 ./src/util/util.cpp
733 2180 21494 total
我需要用python自动获取LOC,我将运行查找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
补充
有了科尼什切夫的暗示,我可以让它工作
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
调用需要shell=True
。否则,您的|wc
将被传递到find
,它将不知道如何处理它(并且可能会将一个错误发送到err
…而您没有打印)
但为什么要掏钱呢?只需在Python中执行所有这些操作(例如,os.walk
替换find
),它将更易于阅读和维护。比如:
import os, re
for dirpath, dirnames, filenames in os.walk(rootpath):
for filename in filenames:
if filename.endswith(".cc"):
with open(os.path.join(dirpath, filename)) as infile:
text = infile.read()
chars = len(text)
lines = sum(1 for x in re.finditer(r"\n", text))
lines += not text.endswith("\n") # count last line if no newline
words = sum(1 for x in re.finditer(r"\w+", text))
# do whatever with these...
必须像上面描述的那样连接两个Popen对象 但我想推荐,因为它更容易用于这些东西