理解Python 2.7中io.open()方法的缓冲参数 [英] Understanding the buffering argument of the io.open() method in Python 2.7

查看:1088
本文介绍了理解Python 2.7中io.open()方法的缓冲参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 方法。

I am trying to understand the the buffering argument of the io.open() method in Python 2.7.

我在Python解释器中执行:

I execute in the Python interpreter:

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()我自己。

then I look at the test.txt file to see how many lines got written, even though I haven't called file.close() yet, and didn't do any manual file.flush() myself.

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

If buffer_size = 4000, I see that 9822 lines got written. However, buffer_size = 8192, I see that 8414 lines got written.

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

I get this behavior in both Windows 7 SP1 x64 Ultimate (Python 2.7.10 x64) and Kubuntu 14.10 Plasma 4 (Python 2.7.10 x64). I don't understand where these numbers (9822 and 8414) come from.

推荐答案

来自文档(重点是我的):


可选的缓冲参数指定文件所需的缓冲区
大小:0表示无缓冲,1表示行缓冲,任何其他正
值表示使用(大约)该大小(以字节为单位)的缓冲区。
负缓冲意味着使用系统默认值,通常为tty设备缓冲
线路,并为其他文件完全缓冲。如果省略
,则使用系统默认值。 [2]

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]

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

I.e: the buffer size is not guaranteed to be what you pass as parameter. It's impossible to predict how much of the buffer is in use and how much has been written to disk as your write overflow the buffer in both case and the buffer size is machine dependent.

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

As you didn't call an explicit flush, part of the buffer has been flushed and another part is still waiting for it to fill before flushing to disk.

这篇关于理解Python 2.7中io.open()方法的缓冲参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆