在`subprocess.call`中使用多个命令

时间:2015-07-21 10:45:32

标签: python

我想使用call创建一个shell管道。例如,我想运行此代码获取具有123的行数:

shell命令是:

grep "123" myfile | wc -l > sum.txt

但" 123"是一个变量,所以我想使用python:

A= ["123","1234","12345"]
for i in A:
   call(["grep", i,"| wc >> sum.txt"])

此代码不起作用!

2 个答案:

答案 0 :(得分:1)

如果您使用管道角色,则需要shell=True,每次使用i时都会传递str.format

 call('grep "{}" myfile | wc >> sum.txt'.format(i),shell=True)

您也可以在没有shell=True的情况下使用python打开文件而不是shell重定向:

from subprocess import Popen, PIPE, check_call

p = Popen(["grep","myfile" i], stdout=PIPE)
with open('sum.txt', "a") as f:
    check_call(["wc"], stdin=p.stdout,stdout=f)

您的>>>也不一样,因此您打开文件的模式取决于您实际想要复制的模式

答案 1 :(得分:1)

call只调用一个可执行文件。你想要的是可执行文件是一个shell(例如bash),它解析命令行。 bash也负责处理管道。您可以使用shell=True选项执行此操作,默认情况下该选项处于关闭状态。

当你给它一个像你一样的数组时,那么你用那些参数来调用那个可执行文件。管道不是争论;并且grep不知道如何管道,也不知道如何调用wc

你可以做到

call(["grep '%s' myfile | wc >> sum.txt" % i, shell=True)
相关问题