python subprocess.call和管道

时间:2017-09-08 13:32:47

标签: python subprocess pipe

我有一个脚本,其中我尝试使用subprocess.call来执行一系列shell命令,但执行时似乎省略了一些命令。

具体做法是:

#!/usr/bin/python
import tempfile
import subprocess
import os
import re


grepfd, grepfpath = tempfile.mkstemp(suffix=".xx")
sedfd,  sedfpath  = tempfile.mkstemp(suffix=".xx")

# grepoutfile = open( grepfpath, 'w')
sedoutfile  = open( sedfpath,  'w' )

subprocess.call(['cp','/Users/bobby/Downloads/sample.txt', grepfpath])

sedcmd = [ 'sort', 
           grepfpath,
           '|', 
           'uniq',
           '|',
           'sed',
           '-e',
           '"s/bigstring of word/ smaller /"',
           '|',
           'column',
           '-t',
           '-s',
           '"=>"' ]

print "sedcmd = ", sedcmd
subprocess.call( ['ls', grepfpath ] )
subprocess.call( ['sort', '|', 'uniq' ], stdin = grepfd )
subprocess.call( sedcmd,  stdout = sedoutfile )

它会将其生成为输出:

python d3.py

sedcmd = ['sort',/ var / folder / 3h / _0xwt5bx0hx8tgx06cmq9h_4f183ql / T / tmp5Gp0ff.xx','|','uniq','|','sed',' - e','“s / bigstring of word / smaller /“','|','column',' - t',' - s','”=>“'] /var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx sort:open failed:|:没有这样的文件或目录
sort:无效选项 - e 尝试`sort --help'获取更多信息。

第一个'排序:打开失败:|:没有这样的文件......来自第一个子进程调用['sort','|','uniq'],stdin = grepfd) 'sort:invalid选项 - e ..来自第二个子进程调用(sedcmd)。

我已经看到很多在这种情况下使用管道的例子 - 所以我做错了什么? 谢谢!

2 个答案:

答案 0 :(得分:2)

这是一个将运行具有任意数量管道的命令的类:

<强> pipeline.py

import shlex
import subprocess

class Pipeline(object):
    def __init__(self, command):
        self.command = command
        self.command_list = self.command.split('|')
        self.output = None
        self.errors = None
        self.status = None
        self.result = None

    def run(self):
        process_list = list()
        previous_process = None
        for command in self.command_list:
            args = shlex.split(command)
            if previous_process is None:
                process = subprocess.Popen(args, stdout=subprocess.PIPE)
            else:
                process = subprocess.Popen(args,
                                           stdin=previous_process.stdout,
                                           stdout=subprocess.PIPE)
            process_list.append(process)
            previous_process = process
        last_process = process_list[-1]
        self.output, self.errors = last_process.communicate()
        self.status = last_process.returncode
        self.result = (0 == self.status)
        return self.result

此示例显示如何使用该类:

<强> harness.py

from pipeline import Pipeline

if __name__ == '__main__':
    command = '|'.join([
        "sort %s",
        "uniq",
        "sed -e 's/bigstring of word/ smaller /'",
        "column -t -s '=>'"
    ])
    command = command % 'sample.txt'
    pipeline = Pipeline(command)
    if not pipeline.run():
        print "ERROR: Pipeline failed"
    else:
        print pipeline.output

我创建了此示例文件以进行测试:

<强> sample.txt的

word1>word2=word3
list1>list2=list3
a>bigstring of word=b
blah1>blah2=blah3

<强>输出

a       smaller   b
blah1  blah2      blah3
list1  list2      list3
word1  word2      word3

答案 1 :(得分:0)

因此,如果在命令中要使用shell管道,则可以在子进程中添加shell = True: 所以它会是这样的:

sedcmd = 'sort /var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx | uniq | sed -e "s/bigstring of word/ smaller /" | column -t -s "=>" '
subprocess.call(sedcmd, shell=True)

但要小心 shell = True 强烈劝阻才能使用它:subprocess official documentation

因此,如果你想使用没有shell = True的管道,你可以在stdout中使用subprocees.PIPE,这里有一个如何做的例子:stackoveflow answer