1

来自文档

readlines(hint=-1)
    Read and return a list of lines from the stream. 
    hint can be specified to control the number of lines read: 
      no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

提示的真正含义是什么?

在某些环境中:

python3 -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
['hello\n', 'hello\n']
(3, 3, 0)

python -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
[u'hello\n', u'hello\n']
(2, 7, 2)

python -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
[u'hello\n']
(2, 6, 6)

为什么要超过 6 个字符?

有人说这取决于缓冲区大小

但在我的机器中,我无法取消缓冲文本 I/O。

>>> import sys
>>> sys.version
'3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> open('/etc/hosts','r',3).readlines(3)
['##\n', '# Host Database\n']
>>> open('/etc/hosts','r',0).readlines(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: can't have unbuffered text I/O
>>> 

还是这种方法的错误?


2013/02/25 更新:

我检查了源代码(来自 python 2.6/2.7/ 3.x),但我无法解释:

def readlines(self, hint=None):
    """Return a list of lines from the stream.

    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.
    """
    if hint is None or hint <= 0:
        return list(self)
    n = 0
    lines = []
    for line in self:
        lines.append(line)
        n += len(line)
        if n >= hint:
            break
    return lines
4

2 回答 2

0

它已记录在案,因此不是错误:

buffering是用于设置缓冲策略的可选整数。传递0以关闭缓冲(仅在二进制模式下允许)1选择行缓冲(仅在文本模式下可用),以及整数 >1 表示固定大小的块缓冲区的大小。

回答您的问题:“为什么超过 6 个字符?”

这也记录在案:readlines总是返回完整的行:

可以指定提示来控制读取的行数:如果到目前为止所有行的总大小(以字节/字符为单位)超过提示,则不会再读取行。

这意味着:阅读另一整行;如果total read size> hint,则停止阅读。

在您的示例中,在读取第一"hello"行之后,尚未超出大小,因此读取了第二行。

于 2013-02-24T10:20:44.123 回答
0

我发现了 StringIO 和 BytesIO 的区别(但我不知道为什么):

首先检查这个(python 2.7/3.3):

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from io import BytesIO,StringIO
>>> print(BytesIO(b'hello\n'*10).readlines(6))
['hello\n']
>>> print(StringIO(u'hello\n'*10).readlines(6))
[u'hello\n', u'hello\n']
>>> 

StringIO 和 BytesIO 的 C 源代码链接在这里:

模块/_io/iobase.c#l591

620     while (1) {
621         PyObject *line = PyIter_Next(self);
622         if (line == NULL) {
623             if (PyErr_Occurred()) {
624                 Py_DECREF(result);
625                 return NULL;
626             }
627             else
628                 break; /* StopIteration raised */
629         }
630 
631         if (PyList_Append(result, line) < 0) {
632             Py_DECREF(line);
633             Py_DECREF(result);
634             return NULL;
635         }
636         length += PyObject_Size(line);
637         Py_DECREF(line);
638 
639         if (length > hint)
640             break;
641     }

模块/_io/bytesio.c#l380

413     while ((n = get_line(self, &output)) != 0) {
414         line = PyBytes_FromStringAndSize(output, n);
415         if (!line)
416             goto on_error;
417         if (PyList_Append(result, line) == -1) {
418             Py_DECREF(line);
419             goto on_error;
420         }
421         Py_DECREF(line);
422         size += n;
423         if (maxsize > 0 && size >= maxsize)
424             break;
425     }
426     return result;
于 2013-02-26T03:35:16.323 回答