gpt4 book ai didi

python 2.7和3.3子进程模块区别

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:01 25 4
gpt4 key购买 nike

我有以下代码

from __future__ import print_function
import subprocess

p = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.kill()
p.wait()
print(p.stdin.write(b'some'))

我用 python 2.7 和 python 3.3 运行它。在 python 2.7 中,当我尝试写入 stdin 时会抛出异常。对于 python 3.3,这段代码打印 4。python 2.7 子进程模块和 python 3.3 有什么区别?

最佳答案

区别在于 bufsize 的默认值。它在 Python 2.7 中为 0(无缓冲),因此 write 导致 EPIPE 错误。管道在 Python 3.2+ 中完全缓冲,即,在您刷新缓冲区之前,不会检测到错误。来自 subprocess' docs :

Changed in version 3.3.1: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected.

关于python 2.7和3.3子进程模块区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20565026/

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