"的奇怪行为-6ren"> "的奇怪行为-我注意到 subprocess.Popen() 调用中的“&>”运算符会立即提供返回代码,即使在直觉上不应该这样做的情况下也是如此。举例说明: >>> import subprocess >>> a -6ren">
gpt4 book ai didi

python - 子进程 Popen 中 "&>"的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:32 24 4
gpt4 key购买 nike

我注意到 subprocess.Popen() 调用中的“&>”运算符会立即提供返回代码,即使在直觉上不应该这样做的情况下也是如此。举例说明:

>>> import subprocess
>>> a = subprocess.Popen("sleep 5 > a.txt", shell = True)
>>> print(a.poll()) # immediately try printing
None
>>> print(a.poll()) # wait 5 seconds
0
>>> a = subprocess.Popen("sleep 5 &> a.txt", shell = True)
>>> print(a.poll()) # immediately try printing
0
>>> a = subprocess.Popen("sleep 5 > a.txt 2>&1", shell = True) # this should be the same as using &>
>>> print(a.poll()) # immediately try printing
None
>>> print(a.poll()) # wait 5 seconds
0

我在 Python 3.5.2 上运行它。我的机器默认运行 bash。

有谁知道为什么子流程在这里不支持正确的“&>”行为?

最佳答案

那是因为 &> 是一个 bashism,当 shell=True

来自subprocess.Popen docs :

The executable argument specifies a replacement program to execute. It is very seldom needed. When shell=False, executable replaces the program to execute specified by args. However, the original args is still passed to the program. Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On POSIX, the args name becomes the display name for the executable in utilities such as ps. If shell=True, on POSIX the executable argument specifies a replacement shell for the default /bin/sh.

修复方法是显式指定executable参数,例如:

subprocess.Popen("sleep 5 &> a.txt", shell=True, executable='/bin/bash')

关于python - 子进程 Popen 中 "&>"的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com