我有以下代码
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 to0
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/