Why does shell=True eat my subprocess.Popen stdout?(为什么 shell=True 会吃掉我的 subprocess.Popen 标准输出?)
问题描述
似乎在链的第一个进程中使用 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
', 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 ('
', None)
shell=True 在第二个进程上似乎并不重要.这是预期的行为吗?
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
,它打印
,这就是为什么你会在输出中看到它.
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
, 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 标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 shell=True 会吃掉我的 subprocess.Popen 标准输出?


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01