在Python中用Popen调用pipe命令

调用包含Popen多个管道的命令以便读取其输出的正确方法是什么? 我试过了:

Popen(shlex.split("mycmd arg1 | mysecondcmd - | thirdcmd -", stdout=PIPE)")

但我不认为shlex.split就在这里。 什么是正确的语法?


你有几个选项 - 你可以传递shell=True

Popen('command1 | command2 | command3',shell=True)

或者,您可以将它分解成一堆Popen调用,将它们的stdout挂接到文档中演示的下一个Popen的stdin。


使用sh模块,管道变成功能组成:

import sh
output = sh.thirdcmd(sh.mysecondcmd(sh.mycmd("arg1")))

如果您希望在没有shell = True情况下使用子进程执行此操作,则文档中会有一个示例显示如何使用subprocess.Popen编写shell管道。 请注意,您应该关闭proc.stdout以便可以正确接收SIGPIPE

import subprocess
proc1 = subprocess.Popen(shlex.split('mycmd arg1'), stdout = subprocess.PIPE)
proc2 = subprocess.Popen(shlex.split('mysecondcmd'), stdin = proc1.PIPE,
                         stdout = subprocess.PIPE)
proc3 = subprocess.Popen(shlex.split('thirdcmd'), stdin = proc2.PIPE,
                         stdout = subprocess.PIPE)

# Allow proc1 to receive a SIGPIPE if proc2 exits.
proc1.stdout.close()
# Allow proc2 to receive a SIGPIPE if proc3 exits.
proc2.stdout.close()
out, err = proc3.communicate()

这可能看起来比使用shell = True更多的工作。 您可能想避免使用shell = True的原因是因为它可能存在安全风险(页面向下为“警告”框),特别是当您运行由(潜在恶意)用户提供的命令时。

链接地址: http://www.djcxy.com/p/77087.html

上一篇: invoking pipe command with Popen in Python

下一篇: Difference Between stdout=subprocess.PIPE and stdout=PIPE