理解 Python 2.7 中 io.open() 方法的缓冲参数

Understanding the buffering argument of the io.open() method in Python 2.7

我正在尝试了解 Python 2.7 中 io.open() 方法的缓冲参数。

我在Python解释器中执行:

import utils
buffer_size = 4000
file = open('test.txt','w', buffer_size)
file.write('\n'.join(map(str, range(10000))))  

然后我查看 test.txt 文件以查看写入了多少行,即使我还没有调用 file.close(),也没有执行任何手动操作 file.flush()我自己。

如果buffer_size = 4000,我看到写了9822行。但是,buffer_size = 8192,我看到写了 8414 行。

我在 Windows 7 SP1 x64 Ultimate (Python 2.7.10 x64) 和 Kubuntu 14.10 Plasma 4 (Python 2.7.10 x64) 中都有这种行为。我不明白这些数字(9822 和 8414)是从哪里来的。

引自 documentation(重点是我的):

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]

即:不能保证缓冲区大小是您作为参数传递的大小。无法预测有多少缓冲区正在使用以及有多少已写入磁盘,因为在这两种情况下写入都会溢出缓冲区,并且缓冲区大小取决于机器。

由于您没有调用显式刷新,缓冲区的一部分已被刷新,而另一部分仍在等待填充,然后再刷新到磁盘。