blob: f75a1e1e6c0c6f2077b576312ecc329d8c30f74f [file] [log] [blame]
Christian Heimes1a6387e2008-03-26 12:49:49 +00001"""
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00002The io module provides the Python interfaces to stream handling. The
3builtin open function is defined in this module.
4
5At the top of the I/O hierarchy is the abstract base class IOBase. It
6defines the basic interface to a stream. Note, however, that there is no
7seperation between reading and writing to streams; implementations are
8allowed to throw an IOError if they do not support a given operation.
9
10Extending IOBase is RawIOBase which deals simply with the reading and
11writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
12an interface to OS files.
13
14BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
15subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
16streams that are readable, writable, and both respectively.
17BufferedRandom provides a buffered interface to random access
18streams. BytesIO is a simple stream of in-memory bytes.
19
20Another IOBase subclass, TextIOBase, deals with the encoding and decoding
21of streams into text. TextIOWrapper, which extends it, is a buffered text
22interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
23is a in-memory stream for text.
24
25Argument names are not part of the specification, and only the arguments
26of open() are intended to be used as keyword arguments.
27
28data:
29
30DEFAULT_BUFFER_SIZE
31
32 An int containing the default buffer size used by the module's buffered
33 I/O classes. open() uses the file's blksize (as obtained by os.stat) if
34 possible.
35"""
36# New I/O library conforming to PEP 3116.
37
38# This is a prototype; hopefully eventually some of this will be
39# reimplemented in C.
40
41# XXX edge cases when switching between reading/writing
42# XXX need to support 1 meaning line-buffered
43# XXX whenever an argument is None, use the default value
44# XXX read/write ops should check readable/writable
45# XXX buffered readinto should work with arbitrary buffer objects
46# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
47# XXX check writable, readable and seekable in appropriate places
Christian Heimes3784c6b2008-03-26 23:13:59 +000048from __future__ import print_function
49from __future__ import unicode_literals
Christian Heimes1a6387e2008-03-26 12:49:49 +000050
51__author__ = ("Guido van Rossum <guido@python.org>, "
52 "Mike Verdone <mike.verdone@gmail.com>, "
53 "Mark Russell <mark.russell@zen.co.uk>")
54
55__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
56 "BytesIO", "StringIO", "BufferedIOBase",
57 "BufferedReader", "BufferedWriter", "BufferedRWPair",
58 "BufferedRandom", "TextIOBase", "TextIOWrapper"]
59
60import os
61import abc
62import sys
63import codecs
64import _fileio
65import warnings
66
67# open() uses st_blksize whenever we can
68DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
69
70# py3k has only new style classes
71__metaclass__ = type
72
73class BlockingIOError(IOError):
74
75 """Exception raised when I/O would block on a non-blocking I/O stream."""
76
77 def __init__(self, errno, strerror, characters_written=0):
78 IOError.__init__(self, errno, strerror)
79 self.characters_written = characters_written
80
81
82def open(file, mode="r", buffering=None, encoding=None, errors=None,
83 newline=None, closefd=True):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +000084 r"""Open file and return a stream. If the file cannot be opened, an IOError is
85 raised.
Christian Heimes1a6387e2008-03-26 12:49:49 +000086
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000087 file is either a string giving the name (and the path if the file
88 isn't in the current working directory) of the file to be opened or an
89 integer file descriptor of the file to be wrapped. (If a file
90 descriptor is given, it is closed when the returned I/O object is
91 closed, unless closefd is set to False.)
Christian Heimes1a6387e2008-03-26 12:49:49 +000092
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000093 mode is an optional string that specifies the mode in which the file
94 is opened. It defaults to 'r' which means open for reading in text
95 mode. Other common values are 'w' for writing (truncating the file if
96 it already exists), and 'a' for appending (which on some Unix systems,
97 means that all writes append to the end of the file regardless of the
98 current seek position). In text mode, if encoding is not specified the
99 encoding used is platform dependent. (For reading and writing raw
100 bytes use binary mode and leave encoding unspecified.) The available
101 modes are:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000102
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000103 ========= ===============================================================
104 Character Meaning
105 --------- ---------------------------------------------------------------
106 'r' open for reading (default)
107 'w' open for writing, truncating the file first
108 'a' open for writing, appending to the end of the file if it exists
109 'b' binary mode
110 't' text mode (default)
111 '+' open a disk file for updating (reading and writing)
112 'U' universal newline mode (for backwards compatibility; unneeded
113 for new code)
114 ========= ===============================================================
Christian Heimes1a6387e2008-03-26 12:49:49 +0000115
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000116 The default mode is 'rt' (open for reading text). For binary random
117 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
118 'r+b' opens the file without truncation.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000119
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000120 Python distinguishes between files opened in binary and text modes,
121 even when the underlying operating system doesn't. Files opened in
122 binary mode (appending 'b' to the mode argument) return contents as
123 bytes objects without any decoding. In text mode (the default, or when
124 't' is appended to the mode argument), the contents of the file are
125 returned as strings, the bytes having been first decoded using a
126 platform-dependent encoding or using the specified encoding if given.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000127
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000128 buffering is an optional integer used to set the buffering policy. By
129 default full buffering is on. Pass 0 to switch buffering off (only
130 allowed in binary mode), 1 to set line buffering, and an integer > 1
131 for full buffering.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000132
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000133 encoding is the name of the encoding used to decode or encode the
134 file. This should only be used in text mode. The default encoding is
135 platform dependent, but any encoding supported by Python can be
136 passed. See the codecs module for the list of supported encodings.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000137
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000138 errors is an optional string that specifies how encoding errors are to
139 be handled---this argument should not be used in binary mode. Pass
140 'strict' to raise a ValueError exception if there is an encoding error
141 (the default of None has the same effect), or pass 'ignore' to ignore
142 errors. (Note that ignoring encoding errors can lead to data loss.)
143 See the documentation for codecs.register for a list of the permitted
144 encoding error strings.
145
146 newline controls how universal newlines works (it only applies to text
147 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
148 follows:
149
150 * On input, if newline is None, universal newlines mode is
151 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
152 these are translated into '\n' before being returned to the
153 caller. If it is '', universal newline mode is enabled, but line
154 endings are returned to the caller untranslated. If it has any of
155 the other legal values, input lines are only terminated by the given
156 string, and the line ending is returned to the caller untranslated.
157
158 * On output, if newline is None, any '\n' characters written are
159 translated to the system default line separator, os.linesep. If
160 newline is '', no translation takes place. If newline is any of the
161 other legal values, any '\n' characters written are translated to
162 the given string.
163
164 If closefd is False, the underlying file descriptor will be kept open
165 when the file is closed. This does not work when a file name is given
166 and must be True in that case.
167
168 open() returns a file object whose type depends on the mode, and
169 through which the standard file operations such as reading and writing
170 are performed. When open() is used to open a file in a text mode ('w',
171 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
172 a file in a binary mode, the returned class varies: in read binary
173 mode, it returns a BufferedReader; in write binary and append binary
174 modes, it returns a BufferedWriter, and in read/write mode, it returns
175 a BufferedRandom.
176
177 It is also possible to use a string or bytearray as a file for both
178 reading and writing. For strings StringIO can be used like a file
179 opened in a text mode, and for bytes a BytesIO can be used like a file
180 opened in a binary mode.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000181 """
Christian Heimes3784c6b2008-03-26 23:13:59 +0000182 if not isinstance(file, (basestring, int)):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000183 raise TypeError("invalid file: %r" % file)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000184 if not isinstance(mode, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000185 raise TypeError("invalid mode: %r" % mode)
186 if buffering is not None and not isinstance(buffering, int):
187 raise TypeError("invalid buffering: %r" % buffering)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000188 if encoding is not None and not isinstance(encoding, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000189 raise TypeError("invalid encoding: %r" % encoding)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000190 if errors is not None and not isinstance(errors, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000191 raise TypeError("invalid errors: %r" % errors)
192 modes = set(mode)
193 if modes - set("arwb+tU") or len(mode) > len(modes):
194 raise ValueError("invalid mode: %r" % mode)
195 reading = "r" in modes
196 writing = "w" in modes
197 appending = "a" in modes
198 updating = "+" in modes
199 text = "t" in modes
200 binary = "b" in modes
201 if "U" in modes:
202 if writing or appending:
203 raise ValueError("can't use U and writing mode at once")
204 reading = True
205 if text and binary:
206 raise ValueError("can't have text and binary mode at once")
207 if reading + writing + appending > 1:
208 raise ValueError("can't have read/write/append mode at once")
209 if not (reading or writing or appending):
210 raise ValueError("must have exactly one of read/write/append mode")
211 if binary and encoding is not None:
212 raise ValueError("binary mode doesn't take an encoding argument")
213 if binary and errors is not None:
214 raise ValueError("binary mode doesn't take an errors argument")
215 if binary and newline is not None:
216 raise ValueError("binary mode doesn't take a newline argument")
217 raw = FileIO(file,
218 (reading and "r" or "") +
219 (writing and "w" or "") +
220 (appending and "a" or "") +
221 (updating and "+" or ""),
222 closefd)
223 if buffering is None:
224 buffering = -1
225 line_buffering = False
226 if buffering == 1 or buffering < 0 and raw.isatty():
227 buffering = -1
228 line_buffering = True
229 if buffering < 0:
230 buffering = DEFAULT_BUFFER_SIZE
231 try:
232 bs = os.fstat(raw.fileno()).st_blksize
233 except (os.error, AttributeError):
234 pass
235 else:
236 if bs > 1:
237 buffering = bs
238 if buffering < 0:
239 raise ValueError("invalid buffering size")
240 if buffering == 0:
241 if binary:
242 raw._name = file
243 raw._mode = mode
244 return raw
245 raise ValueError("can't have unbuffered text I/O")
246 if updating:
247 buffer = BufferedRandom(raw, buffering)
248 elif writing or appending:
249 buffer = BufferedWriter(raw, buffering)
250 elif reading:
251 buffer = BufferedReader(raw, buffering)
252 else:
253 raise ValueError("unknown mode: %r" % mode)
254 if binary:
255 buffer.name = file
256 buffer.mode = mode
257 return buffer
258 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
259 text.name = file
260 text.mode = mode
261 return text
262
263class _DocDescriptor:
264 """Helper for builtins.open.__doc__
265 """
266 def __get__(self, obj, typ):
267 return (
268 "open(file, mode='r', buffering=None, encoding=None, "
269 "errors=None, newline=None, closefd=True)\n\n" +
270 open.__doc__)
271
272class OpenWrapper:
273 """Wrapper for builtins.open
274
275 Trick so that open won't become a bound method when stored
276 as a class variable (as dumbdbm does).
277
278 See initstdio() in Python/pythonrun.c.
279 """
280 __doc__ = _DocDescriptor()
281
282 def __new__(cls, *args, **kwargs):
283 return open(*args, **kwargs)
284
285
286class UnsupportedOperation(ValueError, IOError):
287 pass
288
289
290class IOBase(object):
291
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000292 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000293 bytes. There is no public constructor.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000294
295 This class provides dummy implementations for many methods that
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000296 derived classes can override selectively; the default implementations
297 represent a file that cannot be read, written or seeked.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000298
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000299 Even though IOBase does not declare read, readinto, or write because
300 their signatures will vary, implementations and clients should
301 consider those methods part of the interface. Also, implementations
302 may raise a IOError when operations they do not support are called.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000303
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000304 The basic type used for binary data read from or written to a file is
305 bytes. bytearrays are accepted too, and in some cases (such as
306 readinto) needed. Text I/O classes work with str data.
307
308 Note that calling any method (even inquiries) on a closed stream is
309 undefined. Implementations may raise IOError in this case.
310
311 IOBase (and its subclasses) support the iterator protocol, meaning
312 that an IOBase object can be iterated over yielding the lines in a
313 stream.
314
315 IOBase also supports the :keyword:`with` statement. In this example,
316 fp is closed after the suite of the with statment is complete:
317
318 with open('spam.txt', 'r') as fp:
319 fp.write('Spam and eggs!')
Christian Heimes1a6387e2008-03-26 12:49:49 +0000320 """
321
322 __metaclass__ = abc.ABCMeta
323
324 ### Internal ###
325
326 def _unsupported(self, name):
327 """Internal: raise an exception for unsupported operations."""
328 raise UnsupportedOperation("%s.%s() not supported" %
329 (self.__class__.__name__, name))
330
331 ### Positioning ###
332
333 def seek(self, pos, whence = 0):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000334 """Change stream position.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000335
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000336 Change the stream position to byte offset offset. offset is
337 interpreted relative to the position indicated by whence. Values
338 for whence are:
339
340 * 0 -- start of stream (the default); offset should be zero or positive
341 * 1 -- current stream position; offset may be negative
342 * 2 -- end of stream; offset is usually negative
343
344 Return the new absolute position.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000345 """
346 self._unsupported("seek")
347
348 def tell(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000349 """Return current stream position."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000350 return self.seek(0, 1)
351
352 def truncate(self, pos = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000353 """Truncate file to size bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000354
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000355 Size defaults to the current IO position as reported by tell(). Return
356 the new size.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000357 """
358 self._unsupported("truncate")
359
360 ### Flush and close ###
361
362 def flush(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000363 """Flush write buffers, if applicable.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000364
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000365 This is not implemented for read-only and non-blocking streams.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000366 """
367 # XXX Should this return the number of bytes written???
368
369 __closed = False
370
371 def close(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000372 """Flush and close the IO object.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000373
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000374 This method has no effect if the file is already closed.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000375 """
376 if not self.__closed:
377 try:
378 self.flush()
379 except IOError:
380 pass # If flush() fails, just give up
381 self.__closed = True
382
383 def __del__(self):
384 """Destructor. Calls close()."""
385 # The try/except block is in case this is called at program
386 # exit time, when it's possible that globals have already been
387 # deleted, and then the close() call might fail. Since
388 # there's nothing we can do about such failures and they annoy
389 # the end users, we suppress the traceback.
390 try:
391 self.close()
392 except:
393 pass
394
395 ### Inquiries ###
396
397 def seekable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000398 """Return whether object supports random access.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000399
400 If False, seek(), tell() and truncate() will raise IOError.
401 This method may need to do a test seek().
402 """
403 return False
404
405 def _checkSeekable(self, msg=None):
406 """Internal: raise an IOError if file is not seekable
407 """
408 if not self.seekable():
409 raise IOError("File or stream is not seekable."
410 if msg is None else msg)
411
412
413 def readable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000414 """Return whether object was opened for reading.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000415
416 If False, read() will raise IOError.
417 """
418 return False
419
420 def _checkReadable(self, msg=None):
421 """Internal: raise an IOError if file is not readable
422 """
423 if not self.readable():
424 raise IOError("File or stream is not readable."
425 if msg is None else msg)
426
427 def writable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000428 """Return whether object was opened for writing.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000429
430 If False, write() and truncate() will raise IOError.
431 """
432 return False
433
434 def _checkWritable(self, msg=None):
435 """Internal: raise an IOError if file is not writable
436 """
437 if not self.writable():
438 raise IOError("File or stream is not writable."
439 if msg is None else msg)
440
441 @property
442 def closed(self):
443 """closed: bool. True iff the file has been closed.
444
445 For backwards compatibility, this is a property, not a predicate.
446 """
447 return self.__closed
448
449 def _checkClosed(self, msg=None):
450 """Internal: raise an ValueError if file is closed
451 """
452 if self.closed:
453 raise ValueError("I/O operation on closed file."
454 if msg is None else msg)
455
456 ### Context manager ###
457
458 def __enter__(self):
459 """Context management protocol. Returns self."""
460 self._checkClosed()
461 return self
462
463 def __exit__(self, *args):
464 """Context management protocol. Calls close()"""
465 self.close()
466
467 ### Lower-level APIs ###
468
469 # XXX Should these be present even if unimplemented?
470
471 def fileno(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000472 """Returns underlying file descriptor if one exists.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000473
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000474 An IOError is raised if the IO object does not use a file descriptor.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000475 """
476 self._unsupported("fileno")
477
478 def isatty(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000479 """Return whether this is an 'interactive' stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000480
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000481 Return False if it can't be determined.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000482 """
483 self._checkClosed()
484 return False
485
486 ### Readline[s] and writelines ###
487
488 def readline(self, limit = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000489 r"""Read and return a line from the stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000490
491 If limit is specified, at most limit bytes will be read.
492
493 The line terminator is always b'\n' for binary files; for text
494 files, the newlines argument to open can be used to select the line
495 terminator(s) recognized.
496 """
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000497 self._checkClosed()
Christian Heimes1a6387e2008-03-26 12:49:49 +0000498 if hasattr(self, "peek"):
499 def nreadahead():
500 readahead = self.peek(1)
501 if not readahead:
502 return 1
503 n = (readahead.find(b"\n") + 1) or len(readahead)
504 if limit >= 0:
505 n = min(n, limit)
506 return n
507 else:
508 def nreadahead():
509 return 1
510 if limit is None:
511 limit = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000512 if not isinstance(limit, (int, long)):
513 raise TypeError("limit must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000514 res = bytearray()
515 while limit < 0 or len(res) < limit:
516 b = self.read(nreadahead())
517 if not b:
518 break
519 res += b
520 if res.endswith(b"\n"):
521 break
522 return bytes(res)
523
524 def __iter__(self):
525 self._checkClosed()
526 return self
527
528 def next(self):
529 line = self.readline()
530 if not line:
531 raise StopIteration
532 return line
533
534 def readlines(self, hint=None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000535 """Return a list of lines from the stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000536
537 hint can be specified to control the number of lines read: no more
538 lines will be read if the total size (in bytes/characters) of all
539 lines so far exceeds hint.
540 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000541 if hint is None:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000542 hint = -1
543 if not isinstance(hint, (int, long)):
544 raise TypeError("hint must be an integer")
545 if hint <= 0:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000546 return list(self)
547 n = 0
548 lines = []
549 for line in self:
550 lines.append(line)
551 n += len(line)
552 if n >= hint:
553 break
554 return lines
555
556 def writelines(self, lines):
557 self._checkClosed()
558 for line in lines:
559 self.write(line)
560
561
562class RawIOBase(IOBase):
563
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000564 """Base class for raw binary I/O."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000565
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000566 # The read() method is implemented by calling readinto(); derived
567 # classes that want to support read() only need to implement
568 # readinto() as a primitive operation. In general, readinto() can be
569 # more efficient than read().
Christian Heimes1a6387e2008-03-26 12:49:49 +0000570
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000571 # (It would be tempting to also provide an implementation of
572 # readinto() in terms of read(), in case the latter is a more suitable
573 # primitive operation, but that would lead to nasty recursion in case
574 # a subclass doesn't implement either.)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000575
576 def read(self, n = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000577 """Read and return up to n bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000578
579 Returns an empty bytes array on EOF, or None if the object is
580 set not to block and has no data to read.
581 """
582 if n is None:
583 n = -1
584 if n < 0:
585 return self.readall()
586 b = bytearray(n.__index__())
587 n = self.readinto(b)
588 del b[n:]
589 return bytes(b)
590
591 def readall(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000592 """Read until EOF, using multiple read() call."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000593 res = bytearray()
594 while True:
595 data = self.read(DEFAULT_BUFFER_SIZE)
596 if not data:
597 break
598 res += data
599 return bytes(res)
600
601 def readinto(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000602 """Read up to len(b) bytes into b.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000603
604 Returns number of bytes read (0 for EOF), or None if the object
605 is set not to block as has no data to read.
606 """
607 self._unsupported("readinto")
608
609 def write(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000610 """Write the given buffer to the IO stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000611
612 Returns the number of bytes written, which may be less than len(b).
613 """
614 self._unsupported("write")
615
616
617class FileIO(_fileio._FileIO, RawIOBase):
618
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000619 """Raw I/O implementation for OS files."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000620
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000621 # This multiply inherits from _FileIO and RawIOBase to make
622 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
623 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
624 # to do since _fileio.c is written in C).
Christian Heimes1a6387e2008-03-26 12:49:49 +0000625
626 def close(self):
627 _fileio._FileIO.close(self)
628 RawIOBase.close(self)
629
630 @property
631 def name(self):
632 return self._name
633
634 @property
635 def mode(self):
636 return self._mode
637
638
639class BufferedIOBase(IOBase):
640
641 """Base class for buffered IO objects.
642
643 The main difference with RawIOBase is that the read() method
644 supports omitting the size argument, and does not have a default
645 implementation that defers to readinto().
646
647 In addition, read(), readinto() and write() may raise
648 BlockingIOError if the underlying raw stream is in non-blocking
649 mode and not ready; unlike their raw counterparts, they will never
650 return None.
651
652 A typical implementation should not inherit from a RawIOBase
653 implementation, but wrap one.
654 """
655
656 def read(self, n = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000657 """Read and return up to n bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000658
659 If the argument is omitted, None, or negative, reads and
660 returns all data until EOF.
661
662 If the argument is positive, and the underlying raw stream is
663 not 'interactive', multiple raw reads may be issued to satisfy
664 the byte count (unless EOF is reached first). But for
665 interactive raw streams (XXX and for pipes?), at most one raw
666 read will be issued, and a short result does not imply that
667 EOF is imminent.
668
669 Returns an empty bytes array on EOF.
670
671 Raises BlockingIOError if the underlying raw stream has no
672 data at the moment.
673 """
674 self._unsupported("read")
675
676 def readinto(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000677 """Read up to len(b) bytes into b.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000678
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000679 Like read(), this may issue multiple reads to the underlying raw
680 stream, unless the latter is 'interactive'.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000681
682 Returns the number of bytes read (0 for EOF).
683
684 Raises BlockingIOError if the underlying raw stream has no
685 data at the moment.
686 """
687 # XXX This ought to work with anything that supports the buffer API
688 data = self.read(len(b))
689 n = len(data)
690 try:
691 b[:n] = data
692 except TypeError as err:
693 import array
694 if not isinstance(b, array.array):
695 raise err
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000696 b[:n] = array.array(b'b', data)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000697 return n
698
699 def write(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000700 """Write the given buffer to the IO stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000701
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000702 Return the number of bytes written, which is never less than
Christian Heimes1a6387e2008-03-26 12:49:49 +0000703 len(b).
704
705 Raises BlockingIOError if the buffer is full and the
706 underlying raw stream cannot accept more data at the moment.
707 """
708 self._unsupported("write")
709
710
711class _BufferedIOMixin(BufferedIOBase):
712
713 """A mixin implementation of BufferedIOBase with an underlying raw stream.
714
715 This passes most requests on to the underlying raw stream. It
716 does *not* provide implementations of read(), readinto() or
717 write().
718 """
719
720 def __init__(self, raw):
721 self.raw = raw
722
723 ### Positioning ###
724
725 def seek(self, pos, whence=0):
726 return self.raw.seek(pos, whence)
727
728 def tell(self):
729 return self.raw.tell()
730
731 def truncate(self, pos=None):
732 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
733 # and a flush may be necessary to synch both views of the current
734 # file state.
735 self.flush()
736
737 if pos is None:
738 pos = self.tell()
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000739 # XXX: Should seek() be used, instead of passing the position
740 # XXX directly to truncate?
Christian Heimes1a6387e2008-03-26 12:49:49 +0000741 return self.raw.truncate(pos)
742
743 ### Flush and close ###
744
745 def flush(self):
746 self.raw.flush()
747
748 def close(self):
749 if not self.closed:
750 try:
751 self.flush()
752 except IOError:
753 pass # If flush() fails, just give up
754 self.raw.close()
755
756 ### Inquiries ###
757
758 def seekable(self):
759 return self.raw.seekable()
760
761 def readable(self):
762 return self.raw.readable()
763
764 def writable(self):
765 return self.raw.writable()
766
767 @property
768 def closed(self):
769 return self.raw.closed
770
771 ### Lower-level APIs ###
772
773 def fileno(self):
774 return self.raw.fileno()
775
776 def isatty(self):
777 return self.raw.isatty()
778
779
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000780class _BytesIO(BufferedIOBase):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000781
782 """Buffered I/O implementation using an in-memory bytes buffer."""
783
784 # XXX More docs
785
786 def __init__(self, initial_bytes=None):
787 buf = bytearray()
788 if initial_bytes is not None:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000789 buf += bytearray(initial_bytes)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000790 self._buffer = buf
791 self._pos = 0
792
793 def getvalue(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000794 """Return the bytes value (contents) of the buffer
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000795 """
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000796 if self.closed:
797 raise ValueError("getvalue on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000798 return bytes(self._buffer)
799
800 def read(self, n=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000801 if self.closed:
802 raise ValueError("read from closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000803 if n is None:
804 n = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000805 if not isinstance(n, (int, long)):
806 raise TypeError("argument must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000807 if n < 0:
808 n = len(self._buffer)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000809 if len(self._buffer) <= self._pos:
810 return b""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000811 newpos = min(len(self._buffer), self._pos + n)
812 b = self._buffer[self._pos : newpos]
813 self._pos = newpos
814 return bytes(b)
815
816 def read1(self, n):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000817 """this is the same as read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000818 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000819 return self.read(n)
820
821 def write(self, b):
822 if self.closed:
823 raise ValueError("write to closed file")
824 if isinstance(b, unicode):
825 raise TypeError("can't write unicode to binary stream")
826 n = len(b)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000827 if n == 0:
828 return 0
Alexandre Vassalotti844f7572008-05-10 19:59:16 +0000829 pos = self._pos
830 if pos > len(self._buffer):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000831 # Inserts null bytes between the current end of the file
832 # and the new write position.
Alexandre Vassalotti844f7572008-05-10 19:59:16 +0000833 padding = b'\x00' * (pos - len(self._buffer))
834 self._buffer += padding
835 self._buffer[pos:pos + n] = b
836 self._pos += n
Christian Heimes1a6387e2008-03-26 12:49:49 +0000837 return n
838
839 def seek(self, pos, whence=0):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000840 if self.closed:
841 raise ValueError("seek on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000842 try:
843 pos = pos.__index__()
844 except AttributeError as err:
845 raise TypeError("an integer is required") # from err
846 if whence == 0:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000847 if pos < 0:
848 raise ValueError("negative seek position %r" % (pos,))
849 self._pos = pos
Christian Heimes1a6387e2008-03-26 12:49:49 +0000850 elif whence == 1:
851 self._pos = max(0, self._pos + pos)
852 elif whence == 2:
853 self._pos = max(0, len(self._buffer) + pos)
854 else:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000855 raise ValueError("invalid whence value")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000856 return self._pos
857
858 def tell(self):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000859 if self.closed:
860 raise ValueError("tell on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000861 return self._pos
862
863 def truncate(self, pos=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000864 if self.closed:
865 raise ValueError("truncate on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000866 if pos is None:
867 pos = self._pos
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000868 elif pos < 0:
869 raise ValueError("negative truncate position %r" % (pos,))
Christian Heimes1a6387e2008-03-26 12:49:49 +0000870 del self._buffer[pos:]
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000871 return self.seek(pos)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000872
873 def readable(self):
874 return True
875
876 def writable(self):
877 return True
878
879 def seekable(self):
880 return True
881
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000882# Use the faster implementation of BytesIO if available
883try:
884 import _bytesio
885
886 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
887 __doc__ = _bytesio._BytesIO.__doc__
888
889except ImportError:
890 BytesIO = _BytesIO
891
Christian Heimes1a6387e2008-03-26 12:49:49 +0000892
893class BufferedReader(_BufferedIOMixin):
894
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000895 """BufferedReader(raw[, buffer_size])
896
897 A buffer for a readable, sequential BaseRawIO object.
898
899 The constructor creates a BufferedReader for the given readable raw
900 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
901 is used.
902 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000903
904 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
905 """Create a new buffered reader using the given readable raw IO object.
906 """
907 raw._checkReadable()
908 _BufferedIOMixin.__init__(self, raw)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000909 self.buffer_size = buffer_size
Benjamin Peterson01a24322008-07-28 23:35:27 +0000910 self._reset_read_buf()
911
912 def _reset_read_buf(self):
913 self._read_buf = b""
914 self._read_pos = 0
Christian Heimes1a6387e2008-03-26 12:49:49 +0000915
916 def read(self, n=None):
917 """Read n bytes.
918
919 Returns exactly n bytes of data unless the underlying raw IO
920 stream reaches EOF or if the call would block in non-blocking
921 mode. If n is negative, read until EOF or until read() would
922 block.
923 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000924 nodata_val = b""
Benjamin Peterson01a24322008-07-28 23:35:27 +0000925 empty_values = (b"", None)
926 buf = self._read_buf
927 pos = self._read_pos
928
929 # Special case for when the number of bytes to read is unspecified.
930 if n is None or n == -1:
931 self._reset_read_buf()
932 chunks = [buf[pos:]] # Strip the consumed bytes.
933 current_size = 0
934 while True:
935 # Read until EOF or until read() would block.
936 chunk = self.raw.read()
937 if chunk in empty_values:
938 nodata_val = chunk
939 break
940 current_size += len(chunk)
941 chunks.append(chunk)
942 return b"".join(chunks) or nodata_val
943
944 # The number of bytes to read is specified, return at most n bytes.
945 avail = len(buf) - pos # Length of the available buffered data.
946 if n <= avail:
947 # Fast path: the data to read is fully buffered.
948 self._read_pos += n
949 return buf[pos:pos+n]
950 # Slow path: read from the stream until enough bytes are read,
951 # or until an EOF occurs or until read() would block.
952 chunks = [buf[pos:]]
953 wanted = max(self.buffer_size, n)
954 while avail < n:
955 chunk = self.raw.read(wanted)
956 if chunk in empty_values:
957 nodata_val = chunk
Christian Heimes1a6387e2008-03-26 12:49:49 +0000958 break
Benjamin Peterson01a24322008-07-28 23:35:27 +0000959 avail += len(chunk)
960 chunks.append(chunk)
961 # n is more then avail only when an EOF occurred or when
962 # read() would have blocked.
963 n = min(n, avail)
964 out = b"".join(chunks)
965 self._read_buf = out[n:] # Save the extra data in the buffer.
966 self._read_pos = 0
967 return out[:n] if out else nodata_val
Christian Heimes1a6387e2008-03-26 12:49:49 +0000968
969 def peek(self, n=0):
970 """Returns buffered bytes without advancing the position.
971
972 The argument indicates a desired minimal number of bytes; we
973 do at most one raw read to satisfy it. We never return more
974 than self.buffer_size.
975 """
976 want = min(n, self.buffer_size)
Benjamin Peterson01a24322008-07-28 23:35:27 +0000977 have = len(self._read_buf) - self._read_pos
Christian Heimes1a6387e2008-03-26 12:49:49 +0000978 if have < want:
979 to_read = self.buffer_size - have
980 current = self.raw.read(to_read)
981 if current:
Benjamin Peterson01a24322008-07-28 23:35:27 +0000982 self._read_buf = self._read_buf[self._read_pos:] + current
983 self._read_pos = 0
984 return self._read_buf[self._read_pos:]
Christian Heimes1a6387e2008-03-26 12:49:49 +0000985
986 def read1(self, n):
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000987 """Reads up to n bytes, with at most one read() system call."""
988 # Returns up to n bytes. If at least one byte is buffered, we
989 # only return buffered bytes. Otherwise, we do one raw read.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000990 if n <= 0:
991 return b""
992 self.peek(1)
Benjamin Peterson01a24322008-07-28 23:35:27 +0000993 return self.read(min(n, len(self._read_buf) - self._read_pos))
Christian Heimes1a6387e2008-03-26 12:49:49 +0000994
995 def tell(self):
Benjamin Peterson01a24322008-07-28 23:35:27 +0000996 return self.raw.tell() - len(self._read_buf) + self._read_pos
Christian Heimes1a6387e2008-03-26 12:49:49 +0000997
998 def seek(self, pos, whence=0):
999 if whence == 1:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001000 pos -= len(self._read_buf) - self._read_pos
Christian Heimes1a6387e2008-03-26 12:49:49 +00001001 pos = self.raw.seek(pos, whence)
Benjamin Peterson01a24322008-07-28 23:35:27 +00001002 self._reset_read_buf()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001003 return pos
1004
1005
1006class BufferedWriter(_BufferedIOMixin):
1007
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001008 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001009
1010 The constructor creates a BufferedWriter for the given writeable raw
1011 stream. If the buffer_size is not given, it defaults to
1012 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1013 twice the buffer size.
1014 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001015
1016 def __init__(self, raw,
1017 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1018 raw._checkWritable()
1019 _BufferedIOMixin.__init__(self, raw)
1020 self.buffer_size = buffer_size
1021 self.max_buffer_size = (2*buffer_size
1022 if max_buffer_size is None
1023 else max_buffer_size)
1024 self._write_buf = bytearray()
1025
1026 def write(self, b):
1027 if self.closed:
1028 raise ValueError("write to closed file")
1029 if isinstance(b, unicode):
1030 raise TypeError("can't write unicode to binary stream")
1031 # XXX we can implement some more tricks to try and avoid partial writes
1032 if len(self._write_buf) > self.buffer_size:
1033 # We're full, so let's pre-flush the buffer
1034 try:
1035 self.flush()
1036 except BlockingIOError as e:
1037 # We can't accept anything else.
1038 # XXX Why not just let the exception pass through?
1039 raise BlockingIOError(e.errno, e.strerror, 0)
1040 before = len(self._write_buf)
1041 self._write_buf.extend(b)
1042 written = len(self._write_buf) - before
1043 if len(self._write_buf) > self.buffer_size:
1044 try:
1045 self.flush()
1046 except BlockingIOError as e:
1047 if (len(self._write_buf) > self.max_buffer_size):
1048 # We've hit max_buffer_size. We have to accept a partial
1049 # write and cut back our buffer.
1050 overage = len(self._write_buf) - self.max_buffer_size
1051 self._write_buf = self._write_buf[:self.max_buffer_size]
1052 raise BlockingIOError(e.errno, e.strerror, overage)
1053 return written
1054
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001055 def truncate(self, pos=None):
1056 self.flush()
1057 if pos is None:
1058 pos = self.raw.tell()
1059 return self.raw.truncate(pos)
1060
Christian Heimes1a6387e2008-03-26 12:49:49 +00001061 def flush(self):
1062 if self.closed:
1063 raise ValueError("flush of closed file")
1064 written = 0
1065 try:
1066 while self._write_buf:
1067 n = self.raw.write(self._write_buf)
1068 del self._write_buf[:n]
1069 written += n
1070 except BlockingIOError as e:
1071 n = e.characters_written
1072 del self._write_buf[:n]
1073 written += n
1074 raise BlockingIOError(e.errno, e.strerror, written)
1075
1076 def tell(self):
1077 return self.raw.tell() + len(self._write_buf)
1078
1079 def seek(self, pos, whence=0):
1080 self.flush()
1081 return self.raw.seek(pos, whence)
1082
1083
1084class BufferedRWPair(BufferedIOBase):
1085
1086 """A buffered reader and writer object together.
1087
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001088 A buffered reader object and buffered writer object put together to
1089 form a sequential IO object that can read and write. This is typically
1090 used with a socket or two-way pipe.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001091
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001092 reader and writer are RawIOBase objects that are readable and
1093 writeable respectively. If the buffer_size is omitted it defaults to
1094 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1095 defaults to twice the buffer size.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001096 """
1097
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001098 # XXX The usefulness of this (compared to having two separate IO
1099 # objects) is questionable.
1100
Christian Heimes1a6387e2008-03-26 12:49:49 +00001101 def __init__(self, reader, writer,
1102 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1103 """Constructor.
1104
1105 The arguments are two RawIO instances.
1106 """
1107 reader._checkReadable()
1108 writer._checkWritable()
1109 self.reader = BufferedReader(reader, buffer_size)
1110 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
1111
1112 def read(self, n=None):
1113 if n is None:
1114 n = -1
1115 return self.reader.read(n)
1116
1117 def readinto(self, b):
1118 return self.reader.readinto(b)
1119
1120 def write(self, b):
1121 return self.writer.write(b)
1122
1123 def peek(self, n=0):
1124 return self.reader.peek(n)
1125
1126 def read1(self, n):
1127 return self.reader.read1(n)
1128
1129 def readable(self):
1130 return self.reader.readable()
1131
1132 def writable(self):
1133 return self.writer.writable()
1134
1135 def flush(self):
1136 return self.writer.flush()
1137
1138 def close(self):
1139 self.writer.close()
1140 self.reader.close()
1141
1142 def isatty(self):
1143 return self.reader.isatty() or self.writer.isatty()
1144
1145 @property
1146 def closed(self):
1147 return self.writer.closed()
1148
1149
1150class BufferedRandom(BufferedWriter, BufferedReader):
1151
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001152 """A buffered interface to random access streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001153
1154 The constructor creates a reader and writer for a seekable stream,
1155 raw, given in the first argument. If the buffer_size is omitted it
1156 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1157 writer) defaults to twice the buffer size.
1158 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001159
1160 def __init__(self, raw,
1161 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1162 raw._checkSeekable()
1163 BufferedReader.__init__(self, raw, buffer_size)
1164 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1165
1166 def seek(self, pos, whence=0):
1167 self.flush()
1168 # First do the raw seek, then empty the read buffer, so that
1169 # if the raw seek fails, we don't lose buffered data forever.
1170 pos = self.raw.seek(pos, whence)
Benjamin Peterson01a24322008-07-28 23:35:27 +00001171 self._reset_read_buf()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001172 return pos
1173
1174 def tell(self):
Benjamin Peterson01a24322008-07-28 23:35:27 +00001175 if self._write_buf:
Christian Heimes1a6387e2008-03-26 12:49:49 +00001176 return self.raw.tell() + len(self._write_buf)
1177 else:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001178 return BufferedReader.tell(self)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001179
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001180 def truncate(self, pos=None):
1181 if pos is None:
1182 pos = self.tell()
1183 # Use seek to flush the read buffer.
1184 self.seek(pos)
1185 return BufferedWriter.truncate(self)
1186
Christian Heimes1a6387e2008-03-26 12:49:49 +00001187 def read(self, n=None):
1188 if n is None:
1189 n = -1
1190 self.flush()
1191 return BufferedReader.read(self, n)
1192
1193 def readinto(self, b):
1194 self.flush()
1195 return BufferedReader.readinto(self, b)
1196
1197 def peek(self, n=0):
1198 self.flush()
1199 return BufferedReader.peek(self, n)
1200
1201 def read1(self, n):
1202 self.flush()
1203 return BufferedReader.read1(self, n)
1204
1205 def write(self, b):
1206 if self._read_buf:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001207 # Undo readahead
1208 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1209 self._reset_read_buf()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001210 return BufferedWriter.write(self, b)
1211
1212
1213class TextIOBase(IOBase):
1214
1215 """Base class for text I/O.
1216
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001217 This class provides a character and line based interface to stream
1218 I/O. There is no readinto method because Python's character strings
1219 are immutable. There is no public constructor.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001220 """
1221
1222 def read(self, n = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001223 """Read at most n characters from stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001224
1225 Read from underlying buffer until we have n characters or we hit EOF.
1226 If n is negative or omitted, read until EOF.
1227 """
1228 self._unsupported("read")
1229
1230 def write(self, s):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001231 """Write string s to stream."""
Christian Heimes1a6387e2008-03-26 12:49:49 +00001232 self._unsupported("write")
1233
1234 def truncate(self, pos = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001235 """Truncate size to pos."""
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001236 self._unsupported("truncate")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001237
1238 def readline(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001239 """Read until newline or EOF.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001240
1241 Returns an empty string if EOF is hit immediately.
1242 """
1243 self._unsupported("readline")
1244
1245 @property
1246 def encoding(self):
1247 """Subclasses should override."""
1248 return None
1249
1250 @property
1251 def newlines(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001252 """Line endings translated so far.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001253
1254 Only line endings translated during reading are considered.
1255
1256 Subclasses should override.
1257 """
1258 return None
1259
1260
1261class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1262 """Codec used when reading a file in universal newlines mode.
1263 It wraps another incremental decoder, translating \\r\\n and \\r into \\n.
1264 It also records the types of newlines encountered.
1265 When used with translate=False, it ensures that the newline sequence is
1266 returned in one piece.
1267 """
1268 def __init__(self, decoder, translate, errors='strict'):
1269 codecs.IncrementalDecoder.__init__(self, errors=errors)
1270 self.buffer = b''
1271 self.translate = translate
1272 self.decoder = decoder
1273 self.seennl = 0
1274
1275 def decode(self, input, final=False):
1276 # decode input (with the eventual \r from a previous pass)
1277 if self.buffer:
1278 input = self.buffer + input
1279
1280 output = self.decoder.decode(input, final=final)
1281
1282 # retain last \r even when not translating data:
1283 # then readline() is sure to get \r\n in one pass
1284 if output.endswith("\r") and not final:
1285 output = output[:-1]
1286 self.buffer = b'\r'
1287 else:
1288 self.buffer = b''
1289
1290 # Record which newlines are read
1291 crlf = output.count('\r\n')
1292 cr = output.count('\r') - crlf
1293 lf = output.count('\n') - crlf
1294 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1295 | (crlf and self._CRLF)
1296
1297 if self.translate:
1298 if crlf:
1299 output = output.replace("\r\n", "\n")
1300 if cr:
1301 output = output.replace("\r", "\n")
1302
1303 return output
1304
1305 def getstate(self):
1306 buf, flag = self.decoder.getstate()
1307 return buf + self.buffer, flag
1308
1309 def setstate(self, state):
1310 buf, flag = state
1311 if buf.endswith(b'\r'):
1312 self.buffer = b'\r'
1313 buf = buf[:-1]
1314 else:
1315 self.buffer = b''
1316 self.decoder.setstate((buf, flag))
1317
1318 def reset(self):
1319 self.seennl = 0
1320 self.buffer = b''
1321 self.decoder.reset()
1322
1323 _LF = 1
1324 _CR = 2
1325 _CRLF = 4
1326
1327 @property
1328 def newlines(self):
1329 return (None,
1330 "\n",
1331 "\r",
1332 ("\r", "\n"),
1333 "\r\n",
1334 ("\n", "\r\n"),
1335 ("\r", "\r\n"),
1336 ("\r", "\n", "\r\n")
1337 )[self.seennl]
1338
1339
1340class TextIOWrapper(TextIOBase):
1341
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001342 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001343
1344 encoding gives the name of the encoding that the stream will be
1345 decoded or encoded with. It defaults to locale.getpreferredencoding.
1346
1347 errors determines the strictness of encoding and decoding (see the
1348 codecs.register) and defaults to "strict".
1349
1350 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1351 handling of line endings. If it is None, universal newlines is
1352 enabled. With this enabled, on input, the lines endings '\n', '\r',
1353 or '\r\n' are translated to '\n' before being returned to the
1354 caller. Conversely, on output, '\n' is translated to the system
1355 default line seperator, os.linesep. If newline is any other of its
1356 legal values, that newline becomes the newline when the file is read
1357 and it is returned untranslated. On output, '\n' is converted to the
1358 newline.
1359
1360 If line_buffering is True, a call to flush is implied when a call to
1361 write contains a newline character.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001362 """
1363
1364 _CHUNK_SIZE = 128
1365
1366 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1367 line_buffering=False):
1368 if newline not in (None, "", "\n", "\r", "\r\n"):
1369 raise ValueError("illegal newline value: %r" % (newline,))
1370 if encoding is None:
1371 try:
1372 encoding = os.device_encoding(buffer.fileno())
1373 except (AttributeError, UnsupportedOperation):
1374 pass
1375 if encoding is None:
1376 try:
1377 import locale
1378 except ImportError:
1379 # Importing locale may fail if Python is being built
1380 encoding = "ascii"
1381 else:
1382 encoding = locale.getpreferredencoding()
1383
Christian Heimes3784c6b2008-03-26 23:13:59 +00001384 if not isinstance(encoding, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +00001385 raise ValueError("invalid encoding: %r" % encoding)
1386
1387 if errors is None:
1388 errors = "strict"
1389 else:
Christian Heimes3784c6b2008-03-26 23:13:59 +00001390 if not isinstance(errors, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +00001391 raise ValueError("invalid errors: %r" % errors)
1392
1393 self.buffer = buffer
1394 self._line_buffering = line_buffering
1395 self._encoding = encoding
1396 self._errors = errors
1397 self._readuniversal = not newline
1398 self._readtranslate = newline is None
1399 self._readnl = newline
1400 self._writetranslate = newline != ''
1401 self._writenl = newline or os.linesep
1402 self._encoder = None
1403 self._decoder = None
1404 self._decoded_chars = '' # buffer for text returned from decoder
1405 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1406 self._snapshot = None # info for reconstructing decoder state
1407 self._seekable = self._telling = self.buffer.seekable()
1408
1409 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1410 # where dec_flags is the second (integer) item of the decoder state
1411 # and next_input is the chunk of input bytes that comes next after the
1412 # snapshot point. We use this to reconstruct decoder states in tell().
1413
1414 # Naming convention:
1415 # - "bytes_..." for integer variables that count input bytes
1416 # - "chars_..." for integer variables that count decoded characters
1417
Christian Heimes1a6387e2008-03-26 12:49:49 +00001418 @property
1419 def encoding(self):
1420 return self._encoding
1421
1422 @property
1423 def errors(self):
1424 return self._errors
1425
1426 @property
1427 def line_buffering(self):
1428 return self._line_buffering
1429
1430 def seekable(self):
1431 return self._seekable
1432
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001433 def readable(self):
1434 return self.buffer.readable()
1435
1436 def writable(self):
1437 return self.buffer.writable()
1438
Christian Heimes1a6387e2008-03-26 12:49:49 +00001439 def flush(self):
1440 self.buffer.flush()
1441 self._telling = self._seekable
1442
1443 def close(self):
1444 try:
1445 self.flush()
1446 except:
1447 pass # If flush() fails, just give up
1448 self.buffer.close()
1449
1450 @property
1451 def closed(self):
1452 return self.buffer.closed
1453
1454 def fileno(self):
1455 return self.buffer.fileno()
1456
1457 def isatty(self):
1458 return self.buffer.isatty()
1459
1460 def write(self, s):
1461 if self.closed:
1462 raise ValueError("write to closed file")
1463 if not isinstance(s, unicode):
1464 raise TypeError("can't write %s to text stream" %
1465 s.__class__.__name__)
1466 length = len(s)
1467 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1468 if haslf and self._writetranslate and self._writenl != "\n":
1469 s = s.replace("\n", self._writenl)
1470 encoder = self._encoder or self._get_encoder()
1471 # XXX What if we were just reading?
1472 b = encoder.encode(s)
1473 self.buffer.write(b)
1474 if self._line_buffering and (haslf or "\r" in s):
1475 self.flush()
1476 self._snapshot = None
1477 if self._decoder:
1478 self._decoder.reset()
1479 return length
1480
1481 def _get_encoder(self):
1482 make_encoder = codecs.getincrementalencoder(self._encoding)
1483 self._encoder = make_encoder(self._errors)
1484 return self._encoder
1485
1486 def _get_decoder(self):
1487 make_decoder = codecs.getincrementaldecoder(self._encoding)
1488 decoder = make_decoder(self._errors)
1489 if self._readuniversal:
1490 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1491 self._decoder = decoder
1492 return decoder
1493
1494 # The following three methods implement an ADT for _decoded_chars.
1495 # Text returned from the decoder is buffered here until the client
1496 # requests it by calling our read() or readline() method.
1497 def _set_decoded_chars(self, chars):
1498 """Set the _decoded_chars buffer."""
1499 self._decoded_chars = chars
1500 self._decoded_chars_used = 0
1501
1502 def _get_decoded_chars(self, n=None):
1503 """Advance into the _decoded_chars buffer."""
1504 offset = self._decoded_chars_used
1505 if n is None:
1506 chars = self._decoded_chars[offset:]
1507 else:
1508 chars = self._decoded_chars[offset:offset + n]
1509 self._decoded_chars_used += len(chars)
1510 return chars
1511
1512 def _rewind_decoded_chars(self, n):
1513 """Rewind the _decoded_chars buffer."""
1514 if self._decoded_chars_used < n:
1515 raise AssertionError("rewind decoded_chars out of bounds")
1516 self._decoded_chars_used -= n
1517
1518 def _read_chunk(self):
1519 """
1520 Read and decode the next chunk of data from the BufferedReader.
1521
1522 The return value is True unless EOF was reached. The decoded string
1523 is placed in self._decoded_chars (replacing its previous value).
1524 The entire input chunk is sent to the decoder, though some of it
1525 may remain buffered in the decoder, yet to be converted.
1526 """
1527
1528 if self._decoder is None:
1529 raise ValueError("no decoder")
1530
1531 if self._telling:
1532 # To prepare for tell(), we need to snapshot a point in the
1533 # file where the decoder's input buffer is empty.
1534
1535 dec_buffer, dec_flags = self._decoder.getstate()
1536 # Given this, we know there was a valid snapshot point
1537 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1538
1539 # Read a chunk, decode it, and put the result in self._decoded_chars.
1540 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1541 eof = not input_chunk
1542 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1543
1544 if self._telling:
1545 # At the snapshot point, len(dec_buffer) bytes before the read,
1546 # the next input to be decoded is dec_buffer + input_chunk.
1547 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1548
1549 return not eof
1550
1551 def _pack_cookie(self, position, dec_flags=0,
1552 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1553 # The meaning of a tell() cookie is: seek to position, set the
1554 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1555 # into the decoder with need_eof as the EOF flag, then skip
1556 # chars_to_skip characters of the decoded result. For most simple
1557 # decoders, tell() will often just give a byte offset in the file.
1558 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1559 (chars_to_skip<<192) | bool(need_eof)<<256)
1560
1561 def _unpack_cookie(self, bigint):
1562 rest, position = divmod(bigint, 1<<64)
1563 rest, dec_flags = divmod(rest, 1<<64)
1564 rest, bytes_to_feed = divmod(rest, 1<<64)
1565 need_eof, chars_to_skip = divmod(rest, 1<<64)
1566 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1567
1568 def tell(self):
1569 if not self._seekable:
1570 raise IOError("underlying stream is not seekable")
1571 if not self._telling:
1572 raise IOError("telling position disabled by next() call")
1573 self.flush()
1574 position = self.buffer.tell()
1575 decoder = self._decoder
1576 if decoder is None or self._snapshot is None:
1577 if self._decoded_chars:
1578 # This should never happen.
1579 raise AssertionError("pending decoded text")
1580 return position
1581
1582 # Skip backward to the snapshot point (see _read_chunk).
1583 dec_flags, next_input = self._snapshot
1584 position -= len(next_input)
1585
1586 # How many decoded characters have been used up since the snapshot?
1587 chars_to_skip = self._decoded_chars_used
1588 if chars_to_skip == 0:
1589 # We haven't moved from the snapshot point.
1590 return self._pack_cookie(position, dec_flags)
1591
1592 # Starting from the snapshot position, we will walk the decoder
1593 # forward until it gives us enough decoded characters.
1594 saved_state = decoder.getstate()
1595 try:
1596 # Note our initial start point.
1597 decoder.setstate((b'', dec_flags))
1598 start_pos = position
1599 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1600 need_eof = 0
1601
1602 # Feed the decoder one byte at a time. As we go, note the
1603 # nearest "safe start point" before the current location
1604 # (a point where the decoder has nothing buffered, so seek()
1605 # can safely start from there and advance to this location).
Amaury Forgeot d'Arc7684f852008-05-03 12:21:13 +00001606 for next_byte in next_input:
Christian Heimes1a6387e2008-03-26 12:49:49 +00001607 bytes_fed += 1
1608 chars_decoded += len(decoder.decode(next_byte))
1609 dec_buffer, dec_flags = decoder.getstate()
1610 if not dec_buffer and chars_decoded <= chars_to_skip:
1611 # Decoder buffer is empty, so this is a safe start point.
1612 start_pos += bytes_fed
1613 chars_to_skip -= chars_decoded
1614 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1615 if chars_decoded >= chars_to_skip:
1616 break
1617 else:
1618 # We didn't get enough decoded data; signal EOF to get more.
1619 chars_decoded += len(decoder.decode(b'', final=True))
1620 need_eof = 1
1621 if chars_decoded < chars_to_skip:
1622 raise IOError("can't reconstruct logical file position")
1623
1624 # The returned cookie corresponds to the last safe start point.
1625 return self._pack_cookie(
1626 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1627 finally:
1628 decoder.setstate(saved_state)
1629
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001630 def truncate(self, pos=None):
1631 self.flush()
1632 if pos is None:
1633 pos = self.tell()
1634 self.seek(pos)
1635 return self.buffer.truncate()
1636
Christian Heimes1a6387e2008-03-26 12:49:49 +00001637 def seek(self, cookie, whence=0):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001638 if self.closed:
1639 raise ValueError("tell on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001640 if not self._seekable:
1641 raise IOError("underlying stream is not seekable")
1642 if whence == 1: # seek relative to current position
1643 if cookie != 0:
1644 raise IOError("can't do nonzero cur-relative seeks")
1645 # Seeking to the current position should attempt to
1646 # sync the underlying buffer with the current position.
1647 whence = 0
1648 cookie = self.tell()
1649 if whence == 2: # seek relative to end of file
1650 if cookie != 0:
1651 raise IOError("can't do nonzero end-relative seeks")
1652 self.flush()
1653 position = self.buffer.seek(0, 2)
1654 self._set_decoded_chars('')
1655 self._snapshot = None
1656 if self._decoder:
1657 self._decoder.reset()
1658 return position
1659 if whence != 0:
1660 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1661 (whence,))
1662 if cookie < 0:
1663 raise ValueError("negative seek position %r" % (cookie,))
1664 self.flush()
1665
1666 # The strategy of seek() is to go back to the safe start point
1667 # and replay the effect of read(chars_to_skip) from there.
1668 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1669 self._unpack_cookie(cookie)
1670
1671 # Seek back to the safe start point.
1672 self.buffer.seek(start_pos)
1673 self._set_decoded_chars('')
1674 self._snapshot = None
1675
1676 # Restore the decoder to its state from the safe start point.
1677 if self._decoder or dec_flags or chars_to_skip:
1678 self._decoder = self._decoder or self._get_decoder()
1679 self._decoder.setstate((b'', dec_flags))
1680 self._snapshot = (dec_flags, b'')
1681
1682 if chars_to_skip:
1683 # Just like _read_chunk, feed the decoder and save a snapshot.
1684 input_chunk = self.buffer.read(bytes_to_feed)
1685 self._set_decoded_chars(
1686 self._decoder.decode(input_chunk, need_eof))
1687 self._snapshot = (dec_flags, input_chunk)
1688
1689 # Skip chars_to_skip of the decoded characters.
1690 if len(self._decoded_chars) < chars_to_skip:
1691 raise IOError("can't restore logical file position")
1692 self._decoded_chars_used = chars_to_skip
1693
1694 return cookie
1695
1696 def read(self, n=None):
1697 if n is None:
1698 n = -1
1699 decoder = self._decoder or self._get_decoder()
1700 if n < 0:
1701 # Read everything.
1702 result = (self._get_decoded_chars() +
1703 decoder.decode(self.buffer.read(), final=True))
1704 self._set_decoded_chars('')
1705 self._snapshot = None
1706 return result
1707 else:
1708 # Keep reading chunks until we have n characters to return.
1709 eof = False
1710 result = self._get_decoded_chars(n)
1711 while len(result) < n and not eof:
1712 eof = not self._read_chunk()
1713 result += self._get_decoded_chars(n - len(result))
1714 return result
1715
1716 def next(self):
1717 self._telling = False
1718 line = self.readline()
1719 if not line:
1720 self._snapshot = None
1721 self._telling = self._seekable
1722 raise StopIteration
1723 return line
1724
1725 def readline(self, limit=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001726 if self.closed:
1727 raise ValueError("read from closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001728 if limit is None:
1729 limit = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001730 if not isinstance(limit, (int, long)):
1731 raise TypeError("limit must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001732
1733 # Grab all the decoded text (we will rewind any extra bits later).
1734 line = self._get_decoded_chars()
1735
1736 start = 0
1737 decoder = self._decoder or self._get_decoder()
1738
1739 pos = endpos = None
1740 while True:
1741 if self._readtranslate:
1742 # Newlines are already translated, only search for \n
1743 pos = line.find('\n', start)
1744 if pos >= 0:
1745 endpos = pos + 1
1746 break
1747 else:
1748 start = len(line)
1749
1750 elif self._readuniversal:
1751 # Universal newline search. Find any of \r, \r\n, \n
1752 # The decoder ensures that \r\n are not split in two pieces
1753
1754 # In C we'd look for these in parallel of course.
1755 nlpos = line.find("\n", start)
1756 crpos = line.find("\r", start)
1757 if crpos == -1:
1758 if nlpos == -1:
1759 # Nothing found
1760 start = len(line)
1761 else:
1762 # Found \n
1763 endpos = nlpos + 1
1764 break
1765 elif nlpos == -1:
1766 # Found lone \r
1767 endpos = crpos + 1
1768 break
1769 elif nlpos < crpos:
1770 # Found \n
1771 endpos = nlpos + 1
1772 break
1773 elif nlpos == crpos + 1:
1774 # Found \r\n
1775 endpos = crpos + 2
1776 break
1777 else:
1778 # Found \r
1779 endpos = crpos + 1
1780 break
1781 else:
1782 # non-universal
1783 pos = line.find(self._readnl)
1784 if pos >= 0:
1785 endpos = pos + len(self._readnl)
1786 break
1787
1788 if limit >= 0 and len(line) >= limit:
1789 endpos = limit # reached length limit
1790 break
1791
1792 # No line ending seen yet - get more data
1793 more_line = ''
1794 while self._read_chunk():
1795 if self._decoded_chars:
1796 break
1797 if self._decoded_chars:
1798 line += self._get_decoded_chars()
1799 else:
1800 # end of file
1801 self._set_decoded_chars('')
1802 self._snapshot = None
1803 return line
1804
1805 if limit >= 0 and endpos > limit:
1806 endpos = limit # don't exceed limit
1807
1808 # Rewind _decoded_chars to just after the line ending we found.
1809 self._rewind_decoded_chars(len(line) - endpos)
1810 return line[:endpos]
1811
1812 @property
1813 def newlines(self):
1814 return self._decoder.newlines if self._decoder else None
1815
1816class StringIO(TextIOWrapper):
1817
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001818 """An in-memory stream for text. The initial_value argument sets the
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001819 value of object. The other arguments are like those of TextIOWrapper's
1820 constructor.
1821 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001822
1823 def __init__(self, initial_value="", encoding="utf-8",
1824 errors="strict", newline="\n"):
1825 super(StringIO, self).__init__(BytesIO(),
1826 encoding=encoding,
1827 errors=errors,
1828 newline=newline)
1829 if initial_value:
1830 if not isinstance(initial_value, unicode):
1831 initial_value = unicode(initial_value)
1832 self.write(initial_value)
1833 self.seek(0)
1834
1835 def getvalue(self):
1836 self.flush()
1837 return self.buffer.getvalue().decode(self._encoding, self._errors)