除了 EOF 之外,Python 的 read() 是否总是返回请求的大小?
Python read() 方法的行为与 C 的 read 类似吗?在到达文件的最后一个块之前,它返回的字节数是否可能少于请求的字节数?或者当这些字节存在可供读取时,它是否保证始终返回全部字节数?
Does the Python read() method behave like C's read? Might it return less than the requested number of bytes before the last chunk of the file is reached? Or does it guarantee to always return the full amount of bytes when those bytes exist to be read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,Python 标准库对 file.read([size]) 是这么说的:
从文件中最多读取 size 字节(如果在获取 size 字节之前读取达到 EOF,则读取的字节数会更少)。
如果 size 参数为负数或省略,读取所有数据直到达到 EOF
。 ...立即遇到 EOF 时返回空字符串
。 ...另请注意,在非阻塞模式下,即使没有给出大小参数,返回的数据也可能少于请求的数据。
Well, the Python Standard library says this about file.read([size]):
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
If the size argument is negative or omitted,read all data until EOF is reached
. ...An empty string is returned when EOF is encountered immediately
. ... Also note thatwhen in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.
在 CPython 上,它将始终返回请求的字节数,除非达到 EOF。
On CPython, it will always return the number of bytes requested, unless EOF is reached.
这实际上取决于正在阅读的内容。
默认情况下,python 使用 io.BufferedReader 但不会使用如果您显式关闭缓冲,则为一:
根据文档,
io.BufferedReader
只有在遇到 EOF 或底层操作系统调用会阻塞时才会读取较少的内容:这意味着如果您正在读取常规文件,则 BufferedReader 只有在遇到 EOF 时才会读取较少的内容,因为常规文件不会“阻塞”,即使它们需要时间返回。
但是,如果您正在从 *nix“FIFO”(管道)读取数据,那么如果管道中没有数据等待,io.BufferedReader 将返回少于请求的数据。
如果完全禁用缓冲,那么 read() 将返回操作系统返回的任何内容。即使您正在读取常规文件,返回的内容也可能少于您请求的内容。禁用缓冲时要非常小心。
This really depends on what is being read.
By default python uses a io.BufferedReader but will not use one if you explicitly switch off buffering:
According to the documentation, the
io.BufferedReader
will only read less if it hits the EOF or the underlying OS call would block:That means if you are reading a regular file, the BufferedReader will only read less if it hits the EOF because regular files do not "block", even if they take time to return.
However if you are reading from a *nix "FIFO" (pipe) then the io.BufferedReader will return less than requested if there is no data waiting in the pipe.
If you disable buffering altogether then
read()
will return whatever the OS returns. Even if you are reading regular files, this can return less than you requested. Be very careful when disabling buffering.