2024-10-01 09:28:38 发布
网友
调用包含多个管道到Popen的命令以便可以读取其输出的正确方法是什么?我试过了:
Popen
Popen(shlex.split("mycmd arg1 | mysecondcmd - | thirdcmd -", stdout=PIPE)")
但我不相信shlex.split就在这里。正确的语法是什么?在
shlex.split
您有几个选项可以通过shell=True:
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:
shell = True
subprocess.Popen
proc.stdout
SIGPIPE
这看起来比使用shell = True要多得多。您可能希望避免shell = True的原因是it can be a security risk(向下翻页到“警告”框),特别是当您运行的命令是由(潜在的恶意)用户提供的。在
您有几个选项可以通过
shell=True
:或者,您可以将其分解为一组
Popen
调用,将它们的stdout挂接到下一个Popen的stdin,如documentation所示。在使用sh module,管道成为函数组合:
如果您想用没有
^{pr2}$shell = True
的子进程来完成它,有一个example in the docs,它展示了如何使用subprocess.Popen
编写shell管道。请注意,您应该关闭proc.stdout
s,以便能够正确接收SIGPIPE
s:这看起来比使用
shell = True
要多得多。您可能希望避免shell = True
的原因是it can be a security risk(向下翻页到“警告”框),特别是当您运行的命令是由(潜在的恶意)用户提供的。在相关问题 更多 >
编程相关推荐