在Python中用Popen调用pipe命令

2024-10-01 09:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 方法命令管道stdout语法splitpopenpipe
2条回答

您有几个选项可以通过shell=True

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

或者,您可以将其分解为一组Popen调用,将它们的stdout挂接到下一个Popen的stdin,如documentation所示。在

使用sh module,管道成为函数组合:

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

如果您想用没有shell = True的子进程来完成它,有一个example in the docs,它展示了如何使用subprocess.Popen编写shell管道。请注意,您应该关闭proc.stdouts,以便能够正确接收SIGPIPEs:

^{pr2}$

这看起来比使用shell = True要多得多。您可能希望避免shell = True的原因是it can be a security risk(向下翻页到“警告”框),特别是当您运行的命令是由(潜在的恶意)用户提供的。在

相关问题 更多 >