为什么shell = True吃我的subprocess.Popen stdout? [英] Why does shell=True eat my subprocess.Popen stdout?

查看:187
本文介绍了为什么shell = True吃我的subprocess.Popen stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在链的第一个过程中使用shell = True会以某种方式从下游任务中删除标准输出:

It seems that using shell=True in the first process of a chain somehow drops the stdout from downstream tasks:

p1 = Popen(['echo','hello'], stdout=PIPE)
p2 = Popen('cat', stdin=p1.stdout, stdout=PIPE)
p2.communicate()
# outputs correctly ('hello\n', None)

使第一个进程使用shell = True会以某种方式终止输出...

Making the first process use shell=True kills the output somehow...

p1 = Popen(['echo','hello'], stdout=PIPE, shell=True)
p2 = Popen('cat', stdin=p1.stdout, stdout=PIPE)
p2.communicate()
# outputs incorrectly ('\n', None)

shell =第二步的正确性似乎无关紧要.这是预期的行为吗?

shell=True on the second process doesn't seem to matter. Is this expected behavior?

推荐答案

当您传递shell=True时,Popen需要一个字符串参数,而不是列表.因此,当您执行此操作时:

When you pass shell=True, Popen expects a single string argument, not a list. So when you do this:

p1 = Popen(['echo','hello'], stdout=PIPE, shell=True)

这是怎么回事:

execve("/bin/sh", ["/bin/sh", "-c", "echo", "hello"], ...)

也就是说,它调用sh -c "echo",并且有效地忽略了hello(从技术上讲,它成为shell的位置参数).因此,shell运行echo,并显示\n,这就是为什么在输出中看到它的原因.

That is, it calls sh -c "echo", and hello is effectively ignored (technically it becomes a positional argument to the shell). So the shell runs echo, which prints \n, which is why you see that in your output.

如果使用shell=True,则需要执行以下操作:

If you use shell=True, you need to do this:

  p1 = Popen('echo hello', stdout=PIPE, shell=True)

这篇关于为什么shell = True吃我的subprocess.Popen stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆