如何用|来执行shell命令管道里面

时间:2013-08-05 05:13:08

标签: python shell

我正在使用python的子进程call()来执行shell命令。 它适用于单个命令。 但是,如果我的shell命令调用命令并将其传递给另一个命令,该怎么办呢。

即。我怎么能在python脚本中执行它?

grep -r PASSED *.log | sort -u | wc -l

我正在尝试使用Popen方式,但我总是得到0作为输出

p1 = subprocess.Popen(("xxd -p " + filename).split(), stdout=subprocess.PIPE)
p2 = subprocess.Popen("tr -d \'\\n\'".split(), stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(("grep -c \'"+search_str + "\'").split(), stdin=p2.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
p2.stdout.close()  # Allow p2 to receive a SIGPIPE if p3 exits.
output = p3.communicate()[0]

当我在shell中尝试命令时,它返回1

 xxd -p file_0_4.bin | tr -d '\n'  | grep -c 'f5dfddd239'

我总是得到0.即使我在shell中输入相同的命令时得到1。

3 个答案:

答案 0 :(得分:22)

使用shell=True参数调用。例如,

import subprocess

subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)

艰难的方式

import glob
import subprocess

grep = subprocess.Popen(['grep', '-r', 'PASSED'] + glob.glob('*.log'), stdout=subprocess.PIPE)
sort = subprocess.Popen(['sort', '-u'], stdin=grep.stdout, stdout=subprocess.PIPE)
exit_status = subprocess.call(['wc', '-l'], stdin=sort.stdout)

请参阅Replacing shell pipeline

答案 1 :(得分:4)

其他答案可行。但这是一种更优雅的方法,IMO,即使用plumbum

from plumbum.cmd import grep, sort, wc
cmd = grep['-r']['PASSED']['*.log'] | sort['-u'] | wc['-l']  # construct the command
print cmd() # run the command

答案 2 :(得分:0)

您可能希望查看herehere这是使用“subprocess”与shell = True