io.IOBase.readlines(提示)在python中意味着什么?

时间:2013-02-24 10:01:11

标签: python python-2.7 python-3.x python-2.6 readlines

来自doc

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个字符?

Some one said that depended on buffer size

但在我的机器中,我无法解除文本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更新:

我检查source(来自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

2 个答案:

答案 0 :(得分:0)

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

  

buffering是一个可选的整数,用于设置缓冲策略。   通过0关闭缓冲(仅限二进制模式)1   选择行缓冲(仅在文本模式下可用)和整数&gt; 1   指示固定大小的块缓冲区的大小。

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

还记录了这一点:readlines始终返回完整的行:

  

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

这意味着:阅读另一个整行;如果total read size&gt; hint,然后停止阅读。

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

答案 1 :(得分: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源代码链接在这里:

Modules/_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     }

Modules/_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;