简体   繁体   English

使用subprocess.call进行带有管道重定向的命令

[英]Use subprocess.call for command with a pipe redirection

Having read other answers on here, I know that shell=True is frowned upon, but I am having trouble with a command (more accurately a pair of commands?) with a pipe redirect. 在这里阅读了其他答案后,我知道shell=True令人头疼,但是我在使用带有管道重定向的命令(更准确地说是一对命令?)时遇到了麻烦。

This works: 这有效:

subprocess.call('echo "Test" | mail -s "Test" test@gmail.com', shell=True) 

but this does not: 但这不是:

subprocess.call(["echo", "Test", "|", "mail", "-s", "'Test'", test@gmail.com"]))

Any suggestions on how to make the second one work? 关于如何使第二个奏效的任何建议?

You can do something like below to get a piped output like this: 您可以执行以下操作来获得如下管道输出:

echo "Test" | mail -s "Test" test@gmail.com'

Basically, create multiple subprocess.Popen objects, specify one's stdout as a PIPE, and feed this as an stdin to the other object: 基本上,创建多个subprocess.Popen对象,将一个标准输出指定为PIPE,并将其作为标准输入提供给另一个对象:

p1 = Popen(["echo", "Test"], stdout=PIPE)
p2 = Popen(["mail", "-s", "Test", "test@gmail.com"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

You can check this for more info. 您可以检查此以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM