首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将多个Popen命令与管道链接

将多个Popen命令与管道链接
EN

Stack Overflow用户
提问于 2011-09-12 22:43:57
回答 4查看 32.4K关注 0票数 30

我知道如何使用cmd = subprocess.Popen然后使用subprocess.communicate来运行命令。大多数时候,我使用一个用shlex.split标记的字符串作为Popen的'argv‘参数。以"ls -l“为例:

代码语言:javascript
复制
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]

然而,管道似乎不起作用。例如,下面的示例返回注释:

代码语言:javascript
复制
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]

你能告诉我我哪里做错了吗?

Thx

EN

回答 4

Stack Overflow用户

发布于 2011-09-12 22:58:22

我认为你想在这里实例化两个单独的Popen对象,一个用于'ls‘,另一个用于'sed’。您需要将第一个Popen对象的stdout属性作为stdin参数传递给第二个Popen对象。

示例:

代码语言:javascript
复制
p1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)
p2 = subprocess.Popen('sed ...', stdin=p1.stdout, stdout=subprocess.PIPE)
print p2.communicate()

如果你有更多的命令,你可以继续这样链接:

代码语言:javascript
复制
p3 = subprocess.Popen('prog', stdin=p2.stdout, ...)

有关如何使用子进程的更多信息,请参阅subprocess documentation

票数 46
EN

Stack Overflow用户

发布于 2015-04-21 02:18:30

我做了一个小函数来帮助处理管道,希望它能帮上忙。它将在需要时链接Popen。

代码语言:javascript
复制
from subprocess import Popen, PIPE
import shlex

def run(cmd):
  """Runs the given command locally and returns the output, err and exit_code."""
  if "|" in cmd:    
    cmd_parts = cmd.split('|')
  else:
    cmd_parts = []
    cmd_parts.append(cmd)
  i = 0
  p = {}
  for cmd_part in cmd_parts:
    cmd_part = cmd_part.strip()
    if i == 0:
      p[i]=Popen(shlex.split(cmd_part),stdin=None, stdout=PIPE, stderr=PIPE)
    else:
      p[i]=Popen(shlex.split(cmd_part),stdin=p[i-1].stdout, stdout=PIPE, stderr=PIPE)
    i = i +1
  (output, err) = p[i-1].communicate()
  exit_code = p[0].wait()

  return str(output), str(err), exit_code

output, err, exit_code = run("ls -lha /var/log | grep syslog | grep gz")

if exit_code != 0:
  print "Output:"
  print output
  print "Error:"
  print err
  # Handle error here
else:
  # Be happy :D
  print output
票数 6
EN

Stack Overflow用户

发布于 2017-03-22 07:38:32

代码语言:javascript
复制
"""
Why don't you use shell

"""

def output_shell(line):

    try:
        shell_command = Popen(line, stdout=PIPE, stderr=PIPE, shell=True)
    except OSError:
        return None
    except ValueError:
        return None

    (output, err) = shell_command.communicate()
    shell_command.wait()
    if shell_command.returncode != 0:
        print "Shell command failed to execute"
        return None
    return str(output)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7389662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档