Jak*_*ger 10 python subprocess pipe popen
似乎在链的第一个进程中使用shell = True会以某种方式从下游任务中删除stdout:
p1 = Popen(['echo','hello'], stdout=PIPE)
p2 = Popen('cat', stdin=p1.stdout, stdout=PIPE)
p2.communicate()
# outputs correctly ('hello\n', None)
Run Code Online (Sandbox Code Playgroud)
使第一个进程使用shell = True以某种方式杀死输出...
p1 = Popen(['echo','hello'], stdout=PIPE, shell=True)
p2 = Popen('cat', stdin=p1.stdout, stdout=PIPE)
p2.communicate()
# outputs incorrectly ('\n', None)
Run Code Online (Sandbox Code Playgroud)
shell = True对第二个进程似乎并不重要.这是预期的行为吗?
lar*_*sks 16
当你通过时shell=True,Popen期望一个字符串参数,而不是列表.所以当你这样做时:
p1 = Popen(['echo','hello'], stdout=PIPE, shell=True)
Run Code Online (Sandbox Code Playgroud)
这是怎么回事:
execve("/bin/sh", ["/bin/sh", "-c", "echo", "hello"], ...)
Run Code Online (Sandbox Code Playgroud)
也就是说,它调用sh -c "echo",并被hello有效地忽略(从技术上讲,它成为shell的位置参数).所以shell运行echo,打印\n,这就是你在输出中看到的原因.
如果您使用shell=True,则需要执行以下操作:
p1 = Popen('echo hello', stdout=PIPE, shell=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5458 次 |
| 最近记录: |