blob: 40623d6b5467a0875312140f0ebbf8327f8da625 [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
Jesus Cea585ad8a2009-07-02 15:37:21 +00007separation between reading and writing to streams; implementations are
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00008allowed 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
Christian Heimes1a6387e2008-03-26 12:49:49 +000062import codecs
63import _fileio
Antoine Pitrou11ec65d2008-08-14 21:04:30 +000064import threading
Christian Heimes1a6387e2008-03-26 12:49:49 +000065
66# open() uses st_blksize whenever we can
67DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
68
69# py3k has only new style classes
70__metaclass__ = type
71
72class BlockingIOError(IOError):
73
74 """Exception raised when I/O would block on a non-blocking I/O stream."""
75
76 def __init__(self, errno, strerror, characters_written=0):
77 IOError.__init__(self, errno, strerror)
78 self.characters_written = characters_written
79
80
81def open(file, mode="r", buffering=None, encoding=None, errors=None,
82 newline=None, closefd=True):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +000083 r"""Open file and return a stream. If the file cannot be opened, an IOError is
84 raised.
Christian Heimes1a6387e2008-03-26 12:49:49 +000085
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000086 file is either a string giving the name (and the path if the file
87 isn't in the current working directory) of the file to be opened or an
88 integer file descriptor of the file to be wrapped. (If a file
89 descriptor is given, it is closed when the returned I/O object is
90 closed, unless closefd is set to False.)
Christian Heimes1a6387e2008-03-26 12:49:49 +000091
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000092 mode is an optional string that specifies the mode in which the file
93 is opened. It defaults to 'r' which means open for reading in text
94 mode. Other common values are 'w' for writing (truncating the file if
95 it already exists), and 'a' for appending (which on some Unix systems,
96 means that all writes append to the end of the file regardless of the
97 current seek position). In text mode, if encoding is not specified the
98 encoding used is platform dependent. (For reading and writing raw
99 bytes use binary mode and leave encoding unspecified.) The available
100 modes are:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000101
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000102 ========= ===============================================================
103 Character Meaning
104 --------- ---------------------------------------------------------------
105 'r' open for reading (default)
106 'w' open for writing, truncating the file first
107 'a' open for writing, appending to the end of the file if it exists
108 'b' binary mode
109 't' text mode (default)
110 '+' open a disk file for updating (reading and writing)
111 'U' universal newline mode (for backwards compatibility; unneeded
112 for new code)
113 ========= ===============================================================
Christian Heimes1a6387e2008-03-26 12:49:49 +0000114
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000115 The default mode is 'rt' (open for reading text). For binary random
116 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
117 'r+b' opens the file without truncation.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000118
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000119 Python distinguishes between files opened in binary and text modes,
120 even when the underlying operating system doesn't. Files opened in
121 binary mode (appending 'b' to the mode argument) return contents as
122 bytes objects without any decoding. In text mode (the default, or when
123 't' is appended to the mode argument), the contents of the file are
124 returned as strings, the bytes having been first decoded using a
125 platform-dependent encoding or using the specified encoding if given.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000126
Antoine Pitroub9767262009-12-19 21:03:36 +0000127 buffering is an optional integer used to set the buffering policy.
128 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
129 line buffering (only usable in text mode), and an integer > 1 to indicate
130 the size of a fixed-size chunk buffer. When no buffering argument is
131 given, the default buffering policy works as follows:
132
133 * Binary files are buffered in fixed-size chunks; the size of the buffer
134 is chosen using a heuristic trying to determine the underlying device's
135 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
136 On many systems, the buffer will typically be 4096 or 8192 bytes long.
137
138 * "Interactive" text files (files for which isatty() returns True)
139 use line buffering. Other text files use the policy described above
140 for binary files.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000141
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000142 encoding is the name of the encoding used to decode or encode the
143 file. This should only be used in text mode. The default encoding is
144 platform dependent, but any encoding supported by Python can be
145 passed. See the codecs module for the list of supported encodings.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000146
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000147 errors is an optional string that specifies how encoding errors are to
148 be handled---this argument should not be used in binary mode. Pass
149 'strict' to raise a ValueError exception if there is an encoding error
150 (the default of None has the same effect), or pass 'ignore' to ignore
151 errors. (Note that ignoring encoding errors can lead to data loss.)
152 See the documentation for codecs.register for a list of the permitted
153 encoding error strings.
154
155 newline controls how universal newlines works (it only applies to text
156 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
157 follows:
158
159 * On input, if newline is None, universal newlines mode is
160 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
161 these are translated into '\n' before being returned to the
162 caller. If it is '', universal newline mode is enabled, but line
163 endings are returned to the caller untranslated. If it has any of
164 the other legal values, input lines are only terminated by the given
165 string, and the line ending is returned to the caller untranslated.
166
167 * On output, if newline is None, any '\n' characters written are
168 translated to the system default line separator, os.linesep. If
169 newline is '', no translation takes place. If newline is any of the
170 other legal values, any '\n' characters written are translated to
171 the given string.
172
173 If closefd is False, the underlying file descriptor will be kept open
174 when the file is closed. This does not work when a file name is given
175 and must be True in that case.
176
177 open() returns a file object whose type depends on the mode, and
178 through which the standard file operations such as reading and writing
179 are performed. When open() is used to open a file in a text mode ('w',
180 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
181 a file in a binary mode, the returned class varies: in read binary
182 mode, it returns a BufferedReader; in write binary and append binary
183 modes, it returns a BufferedWriter, and in read/write mode, it returns
184 a BufferedRandom.
185
186 It is also possible to use a string or bytearray as a file for both
187 reading and writing. For strings StringIO can be used like a file
188 opened in a text mode, and for bytes a BytesIO can be used like a file
189 opened in a binary mode.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000190 """
Christian Heimes3784c6b2008-03-26 23:13:59 +0000191 if not isinstance(file, (basestring, int)):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000192 raise TypeError("invalid file: %r" % file)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000193 if not isinstance(mode, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000194 raise TypeError("invalid mode: %r" % mode)
195 if buffering is not None and not isinstance(buffering, int):
196 raise TypeError("invalid buffering: %r" % buffering)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000197 if encoding is not None and not isinstance(encoding, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000198 raise TypeError("invalid encoding: %r" % encoding)
Christian Heimes3784c6b2008-03-26 23:13:59 +0000199 if errors is not None and not isinstance(errors, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000200 raise TypeError("invalid errors: %r" % errors)
201 modes = set(mode)
202 if modes - set("arwb+tU") or len(mode) > len(modes):
203 raise ValueError("invalid mode: %r" % mode)
204 reading = "r" in modes
205 writing = "w" in modes
206 appending = "a" in modes
207 updating = "+" in modes
208 text = "t" in modes
209 binary = "b" in modes
210 if "U" in modes:
211 if writing or appending:
212 raise ValueError("can't use U and writing mode at once")
213 reading = True
214 if text and binary:
215 raise ValueError("can't have text and binary mode at once")
216 if reading + writing + appending > 1:
217 raise ValueError("can't have read/write/append mode at once")
218 if not (reading or writing or appending):
219 raise ValueError("must have exactly one of read/write/append mode")
220 if binary and encoding is not None:
221 raise ValueError("binary mode doesn't take an encoding argument")
222 if binary and errors is not None:
223 raise ValueError("binary mode doesn't take an errors argument")
224 if binary and newline is not None:
225 raise ValueError("binary mode doesn't take a newline argument")
226 raw = FileIO(file,
227 (reading and "r" or "") +
228 (writing and "w" or "") +
229 (appending and "a" or "") +
230 (updating and "+" or ""),
231 closefd)
232 if buffering is None:
233 buffering = -1
234 line_buffering = False
235 if buffering == 1 or buffering < 0 and raw.isatty():
236 buffering = -1
237 line_buffering = True
238 if buffering < 0:
239 buffering = DEFAULT_BUFFER_SIZE
240 try:
241 bs = os.fstat(raw.fileno()).st_blksize
242 except (os.error, AttributeError):
243 pass
244 else:
245 if bs > 1:
246 buffering = bs
247 if buffering < 0:
248 raise ValueError("invalid buffering size")
249 if buffering == 0:
250 if binary:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000251 return raw
252 raise ValueError("can't have unbuffered text I/O")
253 if updating:
254 buffer = BufferedRandom(raw, buffering)
255 elif writing or appending:
256 buffer = BufferedWriter(raw, buffering)
257 elif reading:
258 buffer = BufferedReader(raw, buffering)
259 else:
260 raise ValueError("unknown mode: %r" % mode)
261 if binary:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000262 return buffer
263 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000264 text.mode = mode
265 return text
266
267class _DocDescriptor:
268 """Helper for builtins.open.__doc__
269 """
270 def __get__(self, obj, typ):
271 return (
272 "open(file, mode='r', buffering=None, encoding=None, "
273 "errors=None, newline=None, closefd=True)\n\n" +
274 open.__doc__)
275
276class OpenWrapper:
277 """Wrapper for builtins.open
278
279 Trick so that open won't become a bound method when stored
280 as a class variable (as dumbdbm does).
281
282 See initstdio() in Python/pythonrun.c.
283 """
284 __doc__ = _DocDescriptor()
285
286 def __new__(cls, *args, **kwargs):
287 return open(*args, **kwargs)
288
289
290class UnsupportedOperation(ValueError, IOError):
291 pass
292
293
294class IOBase(object):
295
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000296 """The abstract base class for all I/O classes, acting on streams of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000297 bytes. There is no public constructor.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000298
299 This class provides dummy implementations for many methods that
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000300 derived classes can override selectively; the default implementations
301 represent a file that cannot be read, written or seeked.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000302
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000303 Even though IOBase does not declare read, readinto, or write because
304 their signatures will vary, implementations and clients should
305 consider those methods part of the interface. Also, implementations
306 may raise a IOError when operations they do not support are called.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000307
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000308 The basic type used for binary data read from or written to a file is
309 bytes. bytearrays are accepted too, and in some cases (such as
310 readinto) needed. Text I/O classes work with str data.
311
312 Note that calling any method (even inquiries) on a closed stream is
313 undefined. Implementations may raise IOError in this case.
314
315 IOBase (and its subclasses) support the iterator protocol, meaning
316 that an IOBase object can be iterated over yielding the lines in a
317 stream.
318
319 IOBase also supports the :keyword:`with` statement. In this example,
320 fp is closed after the suite of the with statment is complete:
321
322 with open('spam.txt', 'r') as fp:
323 fp.write('Spam and eggs!')
Christian Heimes1a6387e2008-03-26 12:49:49 +0000324 """
325
326 __metaclass__ = abc.ABCMeta
327
328 ### Internal ###
329
330 def _unsupported(self, name):
331 """Internal: raise an exception for unsupported operations."""
332 raise UnsupportedOperation("%s.%s() not supported" %
333 (self.__class__.__name__, name))
334
335 ### Positioning ###
336
337 def seek(self, pos, whence = 0):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000338 """Change stream position.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000339
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000340 Change the stream position to byte offset offset. offset is
341 interpreted relative to the position indicated by whence. Values
342 for whence are:
343
344 * 0 -- start of stream (the default); offset should be zero or positive
345 * 1 -- current stream position; offset may be negative
346 * 2 -- end of stream; offset is usually negative
347
348 Return the new absolute position.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000349 """
350 self._unsupported("seek")
351
352 def tell(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000353 """Return current stream position."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000354 return self.seek(0, 1)
355
356 def truncate(self, pos = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000357 """Truncate file to size bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000358
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000359 Size defaults to the current IO position as reported by tell(). Return
360 the new size.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000361 """
362 self._unsupported("truncate")
363
364 ### Flush and close ###
365
366 def flush(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000367 """Flush write buffers, if applicable.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000368
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000369 This is not implemented for read-only and non-blocking streams.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000370 """
Antoine Pitrou01a255a2010-05-03 16:48:13 +0000371 if self.__closed:
372 raise ValueError("flush of closed file")
373 #self._checkClosed()
Christian Heimes1a6387e2008-03-26 12:49:49 +0000374 # XXX Should this return the number of bytes written???
375
376 __closed = False
377
378 def close(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000379 """Flush and close the IO object.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000380
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000381 This method has no effect if the file is already closed.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000382 """
383 if not self.__closed:
Antoine Pitrou01a255a2010-05-03 16:48:13 +0000384 self.flush()
Christian Heimes1a6387e2008-03-26 12:49:49 +0000385 self.__closed = True
386
387 def __del__(self):
388 """Destructor. Calls close()."""
389 # The try/except block is in case this is called at program
390 # exit time, when it's possible that globals have already been
391 # deleted, and then the close() call might fail. Since
392 # there's nothing we can do about such failures and they annoy
393 # the end users, we suppress the traceback.
394 try:
395 self.close()
396 except:
397 pass
398
399 ### Inquiries ###
400
401 def seekable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000402 """Return whether object supports random access.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000403
404 If False, seek(), tell() and truncate() will raise IOError.
405 This method may need to do a test seek().
406 """
407 return False
408
409 def _checkSeekable(self, msg=None):
410 """Internal: raise an IOError if file is not seekable
411 """
412 if not self.seekable():
413 raise IOError("File or stream is not seekable."
414 if msg is None else msg)
415
416
417 def readable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000418 """Return whether object was opened for reading.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000419
420 If False, read() will raise IOError.
421 """
422 return False
423
424 def _checkReadable(self, msg=None):
425 """Internal: raise an IOError if file is not readable
426 """
427 if not self.readable():
428 raise IOError("File or stream is not readable."
429 if msg is None else msg)
430
431 def writable(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000432 """Return whether object was opened for writing.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000433
434 If False, write() and truncate() will raise IOError.
435 """
436 return False
437
438 def _checkWritable(self, msg=None):
439 """Internal: raise an IOError if file is not writable
440 """
441 if not self.writable():
442 raise IOError("File or stream is not writable."
443 if msg is None else msg)
444
445 @property
446 def closed(self):
447 """closed: bool. True iff the file has been closed.
448
449 For backwards compatibility, this is a property, not a predicate.
450 """
451 return self.__closed
452
453 def _checkClosed(self, msg=None):
454 """Internal: raise an ValueError if file is closed
455 """
456 if self.closed:
457 raise ValueError("I/O operation on closed file."
458 if msg is None else msg)
459
460 ### Context manager ###
461
462 def __enter__(self):
463 """Context management protocol. Returns self."""
464 self._checkClosed()
465 return self
466
467 def __exit__(self, *args):
468 """Context management protocol. Calls close()"""
469 self.close()
470
471 ### Lower-level APIs ###
472
473 # XXX Should these be present even if unimplemented?
474
475 def fileno(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000476 """Returns underlying file descriptor if one exists.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000477
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000478 An IOError is raised if the IO object does not use a file descriptor.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000479 """
480 self._unsupported("fileno")
481
482 def isatty(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000483 """Return whether this is an 'interactive' stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000484
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000485 Return False if it can't be determined.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000486 """
487 self._checkClosed()
488 return False
489
490 ### Readline[s] and writelines ###
491
492 def readline(self, limit = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000493 r"""Read and return a line from the stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000494
495 If limit is specified, at most limit bytes will be read.
496
497 The line terminator is always b'\n' for binary files; for text
498 files, the newlines argument to open can be used to select the line
499 terminator(s) recognized.
500 """
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000501 self._checkClosed()
Christian Heimes1a6387e2008-03-26 12:49:49 +0000502 if hasattr(self, "peek"):
503 def nreadahead():
504 readahead = self.peek(1)
505 if not readahead:
506 return 1
507 n = (readahead.find(b"\n") + 1) or len(readahead)
508 if limit >= 0:
509 n = min(n, limit)
510 return n
511 else:
512 def nreadahead():
513 return 1
514 if limit is None:
515 limit = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000516 if not isinstance(limit, (int, long)):
517 raise TypeError("limit must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000518 res = bytearray()
519 while limit < 0 or len(res) < limit:
520 b = self.read(nreadahead())
521 if not b:
522 break
523 res += b
524 if res.endswith(b"\n"):
525 break
526 return bytes(res)
527
528 def __iter__(self):
529 self._checkClosed()
530 return self
531
532 def next(self):
533 line = self.readline()
534 if not line:
535 raise StopIteration
536 return line
537
538 def readlines(self, hint=None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000539 """Return a list of lines from the stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000540
541 hint can be specified to control the number of lines read: no more
542 lines will be read if the total size (in bytes/characters) of all
543 lines so far exceeds hint.
544 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000545 if hint is None:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000546 hint = -1
547 if not isinstance(hint, (int, long)):
548 raise TypeError("hint must be an integer")
549 if hint <= 0:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000550 return list(self)
551 n = 0
552 lines = []
553 for line in self:
554 lines.append(line)
555 n += len(line)
556 if n >= hint:
557 break
558 return lines
559
560 def writelines(self, lines):
561 self._checkClosed()
562 for line in lines:
563 self.write(line)
564
565
566class RawIOBase(IOBase):
567
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000568 """Base class for raw binary I/O."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000569
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000570 # The read() method is implemented by calling readinto(); derived
571 # classes that want to support read() only need to implement
572 # readinto() as a primitive operation. In general, readinto() can be
573 # more efficient than read().
Christian Heimes1a6387e2008-03-26 12:49:49 +0000574
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000575 # (It would be tempting to also provide an implementation of
576 # readinto() in terms of read(), in case the latter is a more suitable
577 # primitive operation, but that would lead to nasty recursion in case
578 # a subclass doesn't implement either.)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000579
580 def read(self, n = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000581 """Read and return up to n bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000582
583 Returns an empty bytes array on EOF, or None if the object is
584 set not to block and has no data to read.
585 """
586 if n is None:
587 n = -1
588 if n < 0:
589 return self.readall()
590 b = bytearray(n.__index__())
591 n = self.readinto(b)
592 del b[n:]
593 return bytes(b)
594
595 def readall(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000596 """Read until EOF, using multiple read() call."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000597 res = bytearray()
598 while True:
599 data = self.read(DEFAULT_BUFFER_SIZE)
600 if not data:
601 break
602 res += data
603 return bytes(res)
604
605 def readinto(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000606 """Read up to len(b) bytes into b.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000607
608 Returns number of bytes read (0 for EOF), or None if the object
609 is set not to block as has no data to read.
610 """
611 self._unsupported("readinto")
612
613 def write(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000614 """Write the given buffer to the IO stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000615
616 Returns the number of bytes written, which may be less than len(b).
617 """
618 self._unsupported("write")
619
620
621class FileIO(_fileio._FileIO, RawIOBase):
622
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000623 """Raw I/O implementation for OS files."""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000624
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000625 # This multiply inherits from _FileIO and RawIOBase to make
626 # isinstance(io.FileIO(), io.RawIOBase) return True without requiring
627 # that _fileio._FileIO inherits from io.RawIOBase (which would be hard
628 # to do since _fileio.c is written in C).
Christian Heimes1a6387e2008-03-26 12:49:49 +0000629
Georg Brandld2094602008-12-05 08:51:30 +0000630 def __init__(self, name, mode="r", closefd=True):
631 _fileio._FileIO.__init__(self, name, mode, closefd)
632 self._name = name
633
Christian Heimes1a6387e2008-03-26 12:49:49 +0000634 def close(self):
635 _fileio._FileIO.close(self)
636 RawIOBase.close(self)
637
638 @property
639 def name(self):
640 return self._name
641
Christian Heimes1a6387e2008-03-26 12:49:49 +0000642
643class BufferedIOBase(IOBase):
644
645 """Base class for buffered IO objects.
646
647 The main difference with RawIOBase is that the read() method
648 supports omitting the size argument, and does not have a default
649 implementation that defers to readinto().
650
651 In addition, read(), readinto() and write() may raise
652 BlockingIOError if the underlying raw stream is in non-blocking
653 mode and not ready; unlike their raw counterparts, they will never
654 return None.
655
656 A typical implementation should not inherit from a RawIOBase
657 implementation, but wrap one.
658 """
659
660 def read(self, n = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000661 """Read and return up to n bytes.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000662
663 If the argument is omitted, None, or negative, reads and
664 returns all data until EOF.
665
666 If the argument is positive, and the underlying raw stream is
667 not 'interactive', multiple raw reads may be issued to satisfy
668 the byte count (unless EOF is reached first). But for
669 interactive raw streams (XXX and for pipes?), at most one raw
670 read will be issued, and a short result does not imply that
671 EOF is imminent.
672
673 Returns an empty bytes array on EOF.
674
675 Raises BlockingIOError if the underlying raw stream has no
676 data at the moment.
677 """
678 self._unsupported("read")
679
680 def readinto(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000681 """Read up to len(b) bytes into b.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000682
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000683 Like read(), this may issue multiple reads to the underlying raw
684 stream, unless the latter is 'interactive'.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000685
686 Returns the number of bytes read (0 for EOF).
687
688 Raises BlockingIOError if the underlying raw stream has no
689 data at the moment.
690 """
691 # XXX This ought to work with anything that supports the buffer API
692 data = self.read(len(b))
693 n = len(data)
694 try:
695 b[:n] = data
696 except TypeError as err:
697 import array
698 if not isinstance(b, array.array):
699 raise err
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000700 b[:n] = array.array(b'b', data)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000701 return n
702
703 def write(self, b):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000704 """Write the given buffer to the IO stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +0000705
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000706 Return the number of bytes written, which is never less than
Christian Heimes1a6387e2008-03-26 12:49:49 +0000707 len(b).
708
709 Raises BlockingIOError if the buffer is full and the
710 underlying raw stream cannot accept more data at the moment.
711 """
712 self._unsupported("write")
713
714
715class _BufferedIOMixin(BufferedIOBase):
716
717 """A mixin implementation of BufferedIOBase with an underlying raw stream.
718
719 This passes most requests on to the underlying raw stream. It
720 does *not* provide implementations of read(), readinto() or
721 write().
722 """
723
724 def __init__(self, raw):
725 self.raw = raw
726
727 ### Positioning ###
728
729 def seek(self, pos, whence=0):
730 return self.raw.seek(pos, whence)
731
732 def tell(self):
733 return self.raw.tell()
734
735 def truncate(self, pos=None):
736 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
737 # and a flush may be necessary to synch both views of the current
738 # file state.
739 self.flush()
740
741 if pos is None:
742 pos = self.tell()
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000743 # XXX: Should seek() be used, instead of passing the position
744 # XXX directly to truncate?
Christian Heimes1a6387e2008-03-26 12:49:49 +0000745 return self.raw.truncate(pos)
746
747 ### Flush and close ###
748
749 def flush(self):
750 self.raw.flush()
751
752 def close(self):
753 if not self.closed:
Antoine Pitrou01a255a2010-05-03 16:48:13 +0000754 self.flush()
Christian Heimes1a6387e2008-03-26 12:49:49 +0000755 self.raw.close()
756
757 ### Inquiries ###
758
759 def seekable(self):
760 return self.raw.seekable()
761
762 def readable(self):
763 return self.raw.readable()
764
765 def writable(self):
766 return self.raw.writable()
767
768 @property
769 def closed(self):
770 return self.raw.closed
771
Georg Brandld2094602008-12-05 08:51:30 +0000772 @property
773 def name(self):
774 return self.raw.name
775
776 @property
777 def mode(self):
778 return self.raw.mode
779
Christian Heimes1a6387e2008-03-26 12:49:49 +0000780 ### Lower-level APIs ###
781
782 def fileno(self):
783 return self.raw.fileno()
784
785 def isatty(self):
786 return self.raw.isatty()
787
788
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000789class _BytesIO(BufferedIOBase):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000790
791 """Buffered I/O implementation using an in-memory bytes buffer."""
792
793 # XXX More docs
794
795 def __init__(self, initial_bytes=None):
796 buf = bytearray()
797 if initial_bytes is not None:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000798 buf += bytearray(initial_bytes)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000799 self._buffer = buf
800 self._pos = 0
801
802 def getvalue(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000803 """Return the bytes value (contents) of the buffer
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000804 """
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000805 if self.closed:
806 raise ValueError("getvalue on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000807 return bytes(self._buffer)
808
809 def read(self, n=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000810 if self.closed:
811 raise ValueError("read from closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000812 if n is None:
813 n = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000814 if not isinstance(n, (int, long)):
815 raise TypeError("argument must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000816 if n < 0:
817 n = len(self._buffer)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000818 if len(self._buffer) <= self._pos:
819 return b""
Christian Heimes1a6387e2008-03-26 12:49:49 +0000820 newpos = min(len(self._buffer), self._pos + n)
821 b = self._buffer[self._pos : newpos]
822 self._pos = newpos
823 return bytes(b)
824
825 def read1(self, n):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +0000826 """this is the same as read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000827 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000828 return self.read(n)
829
830 def write(self, b):
831 if self.closed:
832 raise ValueError("write to closed file")
833 if isinstance(b, unicode):
834 raise TypeError("can't write unicode to binary stream")
835 n = len(b)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000836 if n == 0:
837 return 0
Alexandre Vassalotti844f7572008-05-10 19:59:16 +0000838 pos = self._pos
839 if pos > len(self._buffer):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000840 # Inserts null bytes between the current end of the file
841 # and the new write position.
Alexandre Vassalotti844f7572008-05-10 19:59:16 +0000842 padding = b'\x00' * (pos - len(self._buffer))
843 self._buffer += padding
844 self._buffer[pos:pos + n] = b
845 self._pos += n
Christian Heimes1a6387e2008-03-26 12:49:49 +0000846 return n
847
848 def seek(self, pos, whence=0):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000849 if self.closed:
850 raise ValueError("seek on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000851 try:
Ezio Melotti26dfaac2010-08-02 21:35:06 +0000852 pos.__index__
853 except AttributeError:
Christian Heimes1a6387e2008-03-26 12:49:49 +0000854 raise TypeError("an integer is required") # from err
855 if whence == 0:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000856 if pos < 0:
857 raise ValueError("negative seek position %r" % (pos,))
858 self._pos = pos
Christian Heimes1a6387e2008-03-26 12:49:49 +0000859 elif whence == 1:
860 self._pos = max(0, self._pos + pos)
861 elif whence == 2:
862 self._pos = max(0, len(self._buffer) + pos)
863 else:
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000864 raise ValueError("invalid whence value")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000865 return self._pos
866
867 def tell(self):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000868 if self.closed:
869 raise ValueError("tell on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000870 return self._pos
871
872 def truncate(self, pos=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000873 if self.closed:
874 raise ValueError("truncate on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +0000875 if pos is None:
876 pos = self._pos
Ezio Melotti26dfaac2010-08-02 21:35:06 +0000877 else:
878 try:
879 pos.__index__
880 except AttributeError:
881 raise TypeError("an integer is required")
882 if pos < 0:
883 raise ValueError("negative truncate position %r" % (pos,))
Christian Heimes1a6387e2008-03-26 12:49:49 +0000884 del self._buffer[pos:]
Antoine Pitrouca5a06a2010-01-27 21:48:46 +0000885 return pos
Christian Heimes1a6387e2008-03-26 12:49:49 +0000886
887 def readable(self):
888 return True
889
890 def writable(self):
891 return True
892
893 def seekable(self):
894 return True
895
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000896# Use the faster implementation of BytesIO if available
897try:
898 import _bytesio
899
900 class BytesIO(_bytesio._BytesIO, BufferedIOBase):
901 __doc__ = _bytesio._BytesIO.__doc__
902
903except ImportError:
904 BytesIO = _BytesIO
905
Christian Heimes1a6387e2008-03-26 12:49:49 +0000906
907class BufferedReader(_BufferedIOMixin):
908
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000909 """BufferedReader(raw[, buffer_size])
910
911 A buffer for a readable, sequential BaseRawIO object.
912
913 The constructor creates a BufferedReader for the given readable raw
914 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
915 is used.
916 """
Christian Heimes1a6387e2008-03-26 12:49:49 +0000917
918 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
919 """Create a new buffered reader using the given readable raw IO object.
920 """
921 raw._checkReadable()
922 _BufferedIOMixin.__init__(self, raw)
Christian Heimes1a6387e2008-03-26 12:49:49 +0000923 self.buffer_size = buffer_size
Benjamin Peterson01a24322008-07-28 23:35:27 +0000924 self._reset_read_buf()
Antoine Pitrou11ec65d2008-08-14 21:04:30 +0000925 self._read_lock = threading.Lock()
Benjamin Peterson01a24322008-07-28 23:35:27 +0000926
927 def _reset_read_buf(self):
928 self._read_buf = b""
929 self._read_pos = 0
Christian Heimes1a6387e2008-03-26 12:49:49 +0000930
931 def read(self, n=None):
932 """Read n bytes.
933
934 Returns exactly n bytes of data unless the underlying raw IO
935 stream reaches EOF or if the call would block in non-blocking
936 mode. If n is negative, read until EOF or until read() would
937 block.
938 """
Antoine Pitrou11ec65d2008-08-14 21:04:30 +0000939 with self._read_lock:
940 return self._read_unlocked(n)
941
942 def _read_unlocked(self, n=None):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000943 nodata_val = b""
Benjamin Peterson01a24322008-07-28 23:35:27 +0000944 empty_values = (b"", None)
945 buf = self._read_buf
946 pos = self._read_pos
947
948 # Special case for when the number of bytes to read is unspecified.
949 if n is None or n == -1:
950 self._reset_read_buf()
951 chunks = [buf[pos:]] # Strip the consumed bytes.
952 current_size = 0
953 while True:
954 # Read until EOF or until read() would block.
955 chunk = self.raw.read()
956 if chunk in empty_values:
957 nodata_val = chunk
958 break
959 current_size += len(chunk)
960 chunks.append(chunk)
961 return b"".join(chunks) or nodata_val
962
963 # The number of bytes to read is specified, return at most n bytes.
964 avail = len(buf) - pos # Length of the available buffered data.
965 if n <= avail:
966 # Fast path: the data to read is fully buffered.
967 self._read_pos += n
968 return buf[pos:pos+n]
969 # Slow path: read from the stream until enough bytes are read,
970 # or until an EOF occurs or until read() would block.
971 chunks = [buf[pos:]]
972 wanted = max(self.buffer_size, n)
973 while avail < n:
974 chunk = self.raw.read(wanted)
975 if chunk in empty_values:
976 nodata_val = chunk
Christian Heimes1a6387e2008-03-26 12:49:49 +0000977 break
Benjamin Peterson01a24322008-07-28 23:35:27 +0000978 avail += len(chunk)
979 chunks.append(chunk)
980 # n is more then avail only when an EOF occurred or when
981 # read() would have blocked.
982 n = min(n, avail)
983 out = b"".join(chunks)
984 self._read_buf = out[n:] # Save the extra data in the buffer.
985 self._read_pos = 0
986 return out[:n] if out else nodata_val
Christian Heimes1a6387e2008-03-26 12:49:49 +0000987
988 def peek(self, n=0):
989 """Returns buffered bytes without advancing the position.
990
991 The argument indicates a desired minimal number of bytes; we
992 do at most one raw read to satisfy it. We never return more
993 than self.buffer_size.
994 """
Antoine Pitrou11ec65d2008-08-14 21:04:30 +0000995 with self._read_lock:
996 return self._peek_unlocked(n)
997
998 def _peek_unlocked(self, n=0):
Christian Heimes1a6387e2008-03-26 12:49:49 +0000999 want = min(n, self.buffer_size)
Benjamin Peterson01a24322008-07-28 23:35:27 +00001000 have = len(self._read_buf) - self._read_pos
Christian Heimes1a6387e2008-03-26 12:49:49 +00001001 if have < want:
1002 to_read = self.buffer_size - have
1003 current = self.raw.read(to_read)
1004 if current:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001005 self._read_buf = self._read_buf[self._read_pos:] + current
1006 self._read_pos = 0
1007 return self._read_buf[self._read_pos:]
Christian Heimes1a6387e2008-03-26 12:49:49 +00001008
1009 def read1(self, n):
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001010 """Reads up to n bytes, with at most one read() system call."""
1011 # Returns up to n bytes. If at least one byte is buffered, we
1012 # only return buffered bytes. Otherwise, we do one raw read.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001013 if n <= 0:
1014 return b""
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001015 with self._read_lock:
1016 self._peek_unlocked(1)
1017 return self._read_unlocked(
1018 min(n, len(self._read_buf) - self._read_pos))
Christian Heimes1a6387e2008-03-26 12:49:49 +00001019
1020 def tell(self):
Benjamin Peterson01a24322008-07-28 23:35:27 +00001021 return self.raw.tell() - len(self._read_buf) + self._read_pos
Christian Heimes1a6387e2008-03-26 12:49:49 +00001022
1023 def seek(self, pos, whence=0):
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001024 with self._read_lock:
1025 if whence == 1:
1026 pos -= len(self._read_buf) - self._read_pos
1027 pos = self.raw.seek(pos, whence)
1028 self._reset_read_buf()
1029 return pos
Christian Heimes1a6387e2008-03-26 12:49:49 +00001030
1031
1032class BufferedWriter(_BufferedIOMixin):
1033
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001034 """A buffer for a writeable sequential RawIO object.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001035
1036 The constructor creates a BufferedWriter for the given writeable raw
1037 stream. If the buffer_size is not given, it defaults to
1038 DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
1039 twice the buffer size.
1040 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001041
1042 def __init__(self, raw,
1043 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1044 raw._checkWritable()
1045 _BufferedIOMixin.__init__(self, raw)
1046 self.buffer_size = buffer_size
1047 self.max_buffer_size = (2*buffer_size
1048 if max_buffer_size is None
1049 else max_buffer_size)
1050 self._write_buf = bytearray()
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001051 self._write_lock = threading.Lock()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001052
1053 def write(self, b):
1054 if self.closed:
1055 raise ValueError("write to closed file")
1056 if isinstance(b, unicode):
1057 raise TypeError("can't write unicode to binary stream")
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001058 with self._write_lock:
1059 # XXX we can implement some more tricks to try and avoid
1060 # partial writes
1061 if len(self._write_buf) > self.buffer_size:
1062 # We're full, so let's pre-flush the buffer
1063 try:
1064 self._flush_unlocked()
1065 except BlockingIOError as e:
1066 # We can't accept anything else.
1067 # XXX Why not just let the exception pass through?
1068 raise BlockingIOError(e.errno, e.strerror, 0)
1069 before = len(self._write_buf)
1070 self._write_buf.extend(b)
1071 written = len(self._write_buf) - before
1072 if len(self._write_buf) > self.buffer_size:
1073 try:
1074 self._flush_unlocked()
1075 except BlockingIOError as e:
1076 if len(self._write_buf) > self.max_buffer_size:
1077 # We've hit max_buffer_size. We have to accept a
1078 # partial write and cut back our buffer.
1079 overage = len(self._write_buf) - self.max_buffer_size
1080 self._write_buf = self._write_buf[:self.max_buffer_size]
1081 raise BlockingIOError(e.errno, e.strerror, overage)
1082 return written
Christian Heimes1a6387e2008-03-26 12:49:49 +00001083
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001084 def truncate(self, pos=None):
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001085 with self._write_lock:
1086 self._flush_unlocked()
1087 if pos is None:
1088 pos = self.raw.tell()
1089 return self.raw.truncate(pos)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001090
Christian Heimes1a6387e2008-03-26 12:49:49 +00001091 def flush(self):
Antoine Pitrou01a255a2010-05-03 16:48:13 +00001092 if self.closed:
1093 raise ValueError("flush of closed file")
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001094 with self._write_lock:
1095 self._flush_unlocked()
1096
1097 def _flush_unlocked(self):
Christian Heimes1a6387e2008-03-26 12:49:49 +00001098 if self.closed:
1099 raise ValueError("flush of closed file")
1100 written = 0
1101 try:
1102 while self._write_buf:
1103 n = self.raw.write(self._write_buf)
1104 del self._write_buf[:n]
1105 written += n
1106 except BlockingIOError as e:
1107 n = e.characters_written
1108 del self._write_buf[:n]
1109 written += n
1110 raise BlockingIOError(e.errno, e.strerror, written)
1111
1112 def tell(self):
1113 return self.raw.tell() + len(self._write_buf)
1114
1115 def seek(self, pos, whence=0):
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001116 with self._write_lock:
1117 self._flush_unlocked()
1118 return self.raw.seek(pos, whence)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001119
1120
1121class BufferedRWPair(BufferedIOBase):
1122
1123 """A buffered reader and writer object together.
1124
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001125 A buffered reader object and buffered writer object put together to
1126 form a sequential IO object that can read and write. This is typically
1127 used with a socket or two-way pipe.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001128
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001129 reader and writer are RawIOBase objects that are readable and
1130 writeable respectively. If the buffer_size is omitted it defaults to
1131 DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
1132 defaults to twice the buffer size.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001133 """
1134
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001135 # XXX The usefulness of this (compared to having two separate IO
1136 # objects) is questionable.
1137
Christian Heimes1a6387e2008-03-26 12:49:49 +00001138 def __init__(self, reader, writer,
1139 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1140 """Constructor.
1141
1142 The arguments are two RawIO instances.
1143 """
1144 reader._checkReadable()
1145 writer._checkWritable()
1146 self.reader = BufferedReader(reader, buffer_size)
1147 self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
1148
1149 def read(self, n=None):
1150 if n is None:
1151 n = -1
1152 return self.reader.read(n)
1153
1154 def readinto(self, b):
1155 return self.reader.readinto(b)
1156
1157 def write(self, b):
1158 return self.writer.write(b)
1159
1160 def peek(self, n=0):
1161 return self.reader.peek(n)
1162
1163 def read1(self, n):
1164 return self.reader.read1(n)
1165
1166 def readable(self):
1167 return self.reader.readable()
1168
1169 def writable(self):
1170 return self.writer.writable()
1171
1172 def flush(self):
1173 return self.writer.flush()
1174
1175 def close(self):
1176 self.writer.close()
1177 self.reader.close()
1178
1179 def isatty(self):
1180 return self.reader.isatty() or self.writer.isatty()
1181
1182 @property
1183 def closed(self):
Benjamin Peterson828a7062008-12-27 17:05:29 +00001184 return self.writer.closed
Christian Heimes1a6387e2008-03-26 12:49:49 +00001185
1186
1187class BufferedRandom(BufferedWriter, BufferedReader):
1188
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001189 """A buffered interface to random access streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001190
1191 The constructor creates a reader and writer for a seekable stream,
1192 raw, given in the first argument. If the buffer_size is omitted it
1193 defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
1194 writer) defaults to twice the buffer size.
1195 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001196
1197 def __init__(self, raw,
1198 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1199 raw._checkSeekable()
1200 BufferedReader.__init__(self, raw, buffer_size)
1201 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1202
1203 def seek(self, pos, whence=0):
1204 self.flush()
1205 # First do the raw seek, then empty the read buffer, so that
1206 # if the raw seek fails, we don't lose buffered data forever.
Antoine Pitrouc4006102010-05-15 20:33:07 +00001207 if self._read_buf and whence == 1:
1208 # Undo read ahead.
1209 with self._read_lock:
1210 self.raw.seek(self._read_pos - len(self._read_buf), 1)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001211 pos = self.raw.seek(pos, whence)
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001212 with self._read_lock:
1213 self._reset_read_buf()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001214 return pos
1215
1216 def tell(self):
Benjamin Peterson01a24322008-07-28 23:35:27 +00001217 if self._write_buf:
Christian Heimes1a6387e2008-03-26 12:49:49 +00001218 return self.raw.tell() + len(self._write_buf)
1219 else:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001220 return BufferedReader.tell(self)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001221
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001222 def truncate(self, pos=None):
1223 if pos is None:
1224 pos = self.tell()
1225 # Use seek to flush the read buffer.
Antoine Pitrouca5a06a2010-01-27 21:48:46 +00001226 return BufferedWriter.truncate(self, pos)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001227
Christian Heimes1a6387e2008-03-26 12:49:49 +00001228 def read(self, n=None):
1229 if n is None:
1230 n = -1
1231 self.flush()
1232 return BufferedReader.read(self, n)
1233
1234 def readinto(self, b):
1235 self.flush()
1236 return BufferedReader.readinto(self, b)
1237
1238 def peek(self, n=0):
1239 self.flush()
1240 return BufferedReader.peek(self, n)
1241
1242 def read1(self, n):
1243 self.flush()
1244 return BufferedReader.read1(self, n)
1245
1246 def write(self, b):
1247 if self._read_buf:
Benjamin Peterson01a24322008-07-28 23:35:27 +00001248 # Undo readahead
Antoine Pitrou11ec65d2008-08-14 21:04:30 +00001249 with self._read_lock:
1250 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1251 self._reset_read_buf()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001252 return BufferedWriter.write(self, b)
1253
1254
1255class TextIOBase(IOBase):
1256
1257 """Base class for text I/O.
1258
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001259 This class provides a character and line based interface to stream
1260 I/O. There is no readinto method because Python's character strings
1261 are immutable. There is no public constructor.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001262 """
1263
1264 def read(self, n = -1):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001265 """Read at most n characters from stream.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001266
1267 Read from underlying buffer until we have n characters or we hit EOF.
1268 If n is negative or omitted, read until EOF.
1269 """
1270 self._unsupported("read")
1271
1272 def write(self, s):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001273 """Write string s to stream."""
Christian Heimes1a6387e2008-03-26 12:49:49 +00001274 self._unsupported("write")
1275
1276 def truncate(self, pos = None):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001277 """Truncate size to pos."""
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001278 self._unsupported("truncate")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001279
1280 def readline(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001281 """Read until newline or EOF.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001282
1283 Returns an empty string if EOF is hit immediately.
1284 """
1285 self._unsupported("readline")
1286
1287 @property
1288 def encoding(self):
1289 """Subclasses should override."""
1290 return None
1291
1292 @property
1293 def newlines(self):
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001294 """Line endings translated so far.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001295
1296 Only line endings translated during reading are considered.
1297
1298 Subclasses should override.
1299 """
1300 return None
1301
1302
1303class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1304 """Codec used when reading a file in universal newlines mode.
1305 It wraps another incremental decoder, translating \\r\\n and \\r into \\n.
1306 It also records the types of newlines encountered.
1307 When used with translate=False, it ensures that the newline sequence is
1308 returned in one piece.
1309 """
1310 def __init__(self, decoder, translate, errors='strict'):
1311 codecs.IncrementalDecoder.__init__(self, errors=errors)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001312 self.translate = translate
1313 self.decoder = decoder
1314 self.seennl = 0
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001315 self.pendingcr = False
Christian Heimes1a6387e2008-03-26 12:49:49 +00001316
1317 def decode(self, input, final=False):
1318 # decode input (with the eventual \r from a previous pass)
Christian Heimes1a6387e2008-03-26 12:49:49 +00001319 output = self.decoder.decode(input, final=final)
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001320 if self.pendingcr and (output or final):
1321 output = "\r" + output
1322 self.pendingcr = False
Christian Heimes1a6387e2008-03-26 12:49:49 +00001323
1324 # retain last \r even when not translating data:
1325 # then readline() is sure to get \r\n in one pass
1326 if output.endswith("\r") and not final:
1327 output = output[:-1]
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001328 self.pendingcr = True
Christian Heimes1a6387e2008-03-26 12:49:49 +00001329
1330 # Record which newlines are read
1331 crlf = output.count('\r\n')
1332 cr = output.count('\r') - crlf
1333 lf = output.count('\n') - crlf
1334 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1335 | (crlf and self._CRLF)
1336
1337 if self.translate:
1338 if crlf:
1339 output = output.replace("\r\n", "\n")
1340 if cr:
1341 output = output.replace("\r", "\n")
1342
1343 return output
1344
1345 def getstate(self):
1346 buf, flag = self.decoder.getstate()
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001347 flag <<= 1
1348 if self.pendingcr:
1349 flag |= 1
1350 return buf, flag
Christian Heimes1a6387e2008-03-26 12:49:49 +00001351
1352 def setstate(self, state):
1353 buf, flag = state
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001354 self.pendingcr = bool(flag & 1)
1355 self.decoder.setstate((buf, flag >> 1))
Christian Heimes1a6387e2008-03-26 12:49:49 +00001356
1357 def reset(self):
1358 self.seennl = 0
Antoine Pitrouf8638a82008-12-14 18:08:37 +00001359 self.pendingcr = False
Christian Heimes1a6387e2008-03-26 12:49:49 +00001360 self.decoder.reset()
1361
1362 _LF = 1
1363 _CR = 2
1364 _CRLF = 4
1365
1366 @property
1367 def newlines(self):
1368 return (None,
1369 "\n",
1370 "\r",
1371 ("\r", "\n"),
1372 "\r\n",
1373 ("\n", "\r\n"),
1374 ("\r", "\r\n"),
1375 ("\r", "\n", "\r\n")
1376 )[self.seennl]
1377
1378
1379class TextIOWrapper(TextIOBase):
1380
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001381 r"""Character and line based layer over a BufferedIOBase object, buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001382
1383 encoding gives the name of the encoding that the stream will be
1384 decoded or encoded with. It defaults to locale.getpreferredencoding.
1385
1386 errors determines the strictness of encoding and decoding (see the
1387 codecs.register) and defaults to "strict".
1388
1389 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1390 handling of line endings. If it is None, universal newlines is
1391 enabled. With this enabled, on input, the lines endings '\n', '\r',
1392 or '\r\n' are translated to '\n' before being returned to the
1393 caller. Conversely, on output, '\n' is translated to the system
Jesus Cea585ad8a2009-07-02 15:37:21 +00001394 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001395 legal values, that newline becomes the newline when the file is read
1396 and it is returned untranslated. On output, '\n' is converted to the
1397 newline.
1398
1399 If line_buffering is True, a call to flush is implied when a call to
1400 write contains a newline character.
Christian Heimes1a6387e2008-03-26 12:49:49 +00001401 """
1402
1403 _CHUNK_SIZE = 128
1404
1405 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1406 line_buffering=False):
1407 if newline not in (None, "", "\n", "\r", "\r\n"):
1408 raise ValueError("illegal newline value: %r" % (newline,))
1409 if encoding is None:
1410 try:
1411 encoding = os.device_encoding(buffer.fileno())
1412 except (AttributeError, UnsupportedOperation):
1413 pass
1414 if encoding is None:
1415 try:
1416 import locale
1417 except ImportError:
1418 # Importing locale may fail if Python is being built
1419 encoding = "ascii"
1420 else:
1421 encoding = locale.getpreferredencoding()
1422
Christian Heimes3784c6b2008-03-26 23:13:59 +00001423 if not isinstance(encoding, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +00001424 raise ValueError("invalid encoding: %r" % encoding)
1425
1426 if errors is None:
1427 errors = "strict"
1428 else:
Christian Heimes3784c6b2008-03-26 23:13:59 +00001429 if not isinstance(errors, basestring):
Christian Heimes1a6387e2008-03-26 12:49:49 +00001430 raise ValueError("invalid errors: %r" % errors)
1431
1432 self.buffer = buffer
1433 self._line_buffering = line_buffering
1434 self._encoding = encoding
1435 self._errors = errors
1436 self._readuniversal = not newline
1437 self._readtranslate = newline is None
1438 self._readnl = newline
1439 self._writetranslate = newline != ''
1440 self._writenl = newline or os.linesep
1441 self._encoder = None
1442 self._decoder = None
1443 self._decoded_chars = '' # buffer for text returned from decoder
1444 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1445 self._snapshot = None # info for reconstructing decoder state
1446 self._seekable = self._telling = self.buffer.seekable()
1447
Victor Stinner8243ddb2010-07-28 01:58:41 +00001448 if self._seekable and self.writable():
1449 position = self.buffer.tell()
1450 if position != 0:
1451 try:
1452 self._get_encoder().setstate(0)
1453 except LookupError:
1454 # Sometimes the encoder doesn't exist
1455 pass
1456
Christian Heimes1a6387e2008-03-26 12:49:49 +00001457 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1458 # where dec_flags is the second (integer) item of the decoder state
1459 # and next_input is the chunk of input bytes that comes next after the
1460 # snapshot point. We use this to reconstruct decoder states in tell().
1461
1462 # Naming convention:
1463 # - "bytes_..." for integer variables that count input bytes
1464 # - "chars_..." for integer variables that count decoded characters
1465
Christian Heimes1a6387e2008-03-26 12:49:49 +00001466 @property
1467 def encoding(self):
1468 return self._encoding
1469
1470 @property
1471 def errors(self):
1472 return self._errors
1473
1474 @property
1475 def line_buffering(self):
1476 return self._line_buffering
1477
1478 def seekable(self):
1479 return self._seekable
1480
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001481 def readable(self):
1482 return self.buffer.readable()
1483
1484 def writable(self):
1485 return self.buffer.writable()
1486
Christian Heimes1a6387e2008-03-26 12:49:49 +00001487 def flush(self):
1488 self.buffer.flush()
1489 self._telling = self._seekable
1490
1491 def close(self):
Antoine Pitrou01a255a2010-05-03 16:48:13 +00001492 if not self.closed:
Christian Heimes1a6387e2008-03-26 12:49:49 +00001493 self.flush()
Antoine Pitrou01a255a2010-05-03 16:48:13 +00001494 self.buffer.close()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001495
1496 @property
1497 def closed(self):
1498 return self.buffer.closed
1499
Georg Brandld2094602008-12-05 08:51:30 +00001500 @property
1501 def name(self):
1502 return self.buffer.name
1503
Christian Heimes1a6387e2008-03-26 12:49:49 +00001504 def fileno(self):
1505 return self.buffer.fileno()
1506
1507 def isatty(self):
1508 return self.buffer.isatty()
1509
1510 def write(self, s):
1511 if self.closed:
1512 raise ValueError("write to closed file")
1513 if not isinstance(s, unicode):
1514 raise TypeError("can't write %s to text stream" %
1515 s.__class__.__name__)
1516 length = len(s)
1517 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1518 if haslf and self._writetranslate and self._writenl != "\n":
1519 s = s.replace("\n", self._writenl)
1520 encoder = self._encoder or self._get_encoder()
1521 # XXX What if we were just reading?
1522 b = encoder.encode(s)
1523 self.buffer.write(b)
1524 if self._line_buffering and (haslf or "\r" in s):
1525 self.flush()
1526 self._snapshot = None
1527 if self._decoder:
1528 self._decoder.reset()
1529 return length
1530
1531 def _get_encoder(self):
1532 make_encoder = codecs.getincrementalencoder(self._encoding)
1533 self._encoder = make_encoder(self._errors)
1534 return self._encoder
1535
1536 def _get_decoder(self):
1537 make_decoder = codecs.getincrementaldecoder(self._encoding)
1538 decoder = make_decoder(self._errors)
1539 if self._readuniversal:
1540 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1541 self._decoder = decoder
1542 return decoder
1543
1544 # The following three methods implement an ADT for _decoded_chars.
1545 # Text returned from the decoder is buffered here until the client
1546 # requests it by calling our read() or readline() method.
1547 def _set_decoded_chars(self, chars):
1548 """Set the _decoded_chars buffer."""
1549 self._decoded_chars = chars
1550 self._decoded_chars_used = 0
1551
1552 def _get_decoded_chars(self, n=None):
1553 """Advance into the _decoded_chars buffer."""
1554 offset = self._decoded_chars_used
1555 if n is None:
1556 chars = self._decoded_chars[offset:]
1557 else:
1558 chars = self._decoded_chars[offset:offset + n]
1559 self._decoded_chars_used += len(chars)
1560 return chars
1561
1562 def _rewind_decoded_chars(self, n):
1563 """Rewind the _decoded_chars buffer."""
1564 if self._decoded_chars_used < n:
1565 raise AssertionError("rewind decoded_chars out of bounds")
1566 self._decoded_chars_used -= n
1567
1568 def _read_chunk(self):
1569 """
1570 Read and decode the next chunk of data from the BufferedReader.
1571
1572 The return value is True unless EOF was reached. The decoded string
1573 is placed in self._decoded_chars (replacing its previous value).
1574 The entire input chunk is sent to the decoder, though some of it
1575 may remain buffered in the decoder, yet to be converted.
1576 """
1577
1578 if self._decoder is None:
1579 raise ValueError("no decoder")
1580
1581 if self._telling:
1582 # To prepare for tell(), we need to snapshot a point in the
1583 # file where the decoder's input buffer is empty.
1584
1585 dec_buffer, dec_flags = self._decoder.getstate()
1586 # Given this, we know there was a valid snapshot point
1587 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1588
1589 # Read a chunk, decode it, and put the result in self._decoded_chars.
1590 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1591 eof = not input_chunk
1592 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1593
1594 if self._telling:
1595 # At the snapshot point, len(dec_buffer) bytes before the read,
1596 # the next input to be decoded is dec_buffer + input_chunk.
1597 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1598
1599 return not eof
1600
1601 def _pack_cookie(self, position, dec_flags=0,
1602 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1603 # The meaning of a tell() cookie is: seek to position, set the
1604 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1605 # into the decoder with need_eof as the EOF flag, then skip
1606 # chars_to_skip characters of the decoded result. For most simple
1607 # decoders, tell() will often just give a byte offset in the file.
1608 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1609 (chars_to_skip<<192) | bool(need_eof)<<256)
1610
1611 def _unpack_cookie(self, bigint):
1612 rest, position = divmod(bigint, 1<<64)
1613 rest, dec_flags = divmod(rest, 1<<64)
1614 rest, bytes_to_feed = divmod(rest, 1<<64)
1615 need_eof, chars_to_skip = divmod(rest, 1<<64)
1616 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1617
1618 def tell(self):
1619 if not self._seekable:
1620 raise IOError("underlying stream is not seekable")
1621 if not self._telling:
1622 raise IOError("telling position disabled by next() call")
1623 self.flush()
1624 position = self.buffer.tell()
1625 decoder = self._decoder
1626 if decoder is None or self._snapshot is None:
1627 if self._decoded_chars:
1628 # This should never happen.
1629 raise AssertionError("pending decoded text")
1630 return position
1631
1632 # Skip backward to the snapshot point (see _read_chunk).
1633 dec_flags, next_input = self._snapshot
1634 position -= len(next_input)
1635
1636 # How many decoded characters have been used up since the snapshot?
1637 chars_to_skip = self._decoded_chars_used
1638 if chars_to_skip == 0:
1639 # We haven't moved from the snapshot point.
1640 return self._pack_cookie(position, dec_flags)
1641
1642 # Starting from the snapshot position, we will walk the decoder
1643 # forward until it gives us enough decoded characters.
1644 saved_state = decoder.getstate()
1645 try:
1646 # Note our initial start point.
1647 decoder.setstate((b'', dec_flags))
1648 start_pos = position
1649 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1650 need_eof = 0
1651
1652 # Feed the decoder one byte at a time. As we go, note the
1653 # nearest "safe start point" before the current location
1654 # (a point where the decoder has nothing buffered, so seek()
1655 # can safely start from there and advance to this location).
Amaury Forgeot d'Arc7684f852008-05-03 12:21:13 +00001656 for next_byte in next_input:
Christian Heimes1a6387e2008-03-26 12:49:49 +00001657 bytes_fed += 1
1658 chars_decoded += len(decoder.decode(next_byte))
1659 dec_buffer, dec_flags = decoder.getstate()
1660 if not dec_buffer and chars_decoded <= chars_to_skip:
1661 # Decoder buffer is empty, so this is a safe start point.
1662 start_pos += bytes_fed
1663 chars_to_skip -= chars_decoded
1664 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1665 if chars_decoded >= chars_to_skip:
1666 break
1667 else:
1668 # We didn't get enough decoded data; signal EOF to get more.
1669 chars_decoded += len(decoder.decode(b'', final=True))
1670 need_eof = 1
1671 if chars_decoded < chars_to_skip:
1672 raise IOError("can't reconstruct logical file position")
1673
1674 # The returned cookie corresponds to the last safe start point.
1675 return self._pack_cookie(
1676 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1677 finally:
1678 decoder.setstate(saved_state)
1679
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001680 def truncate(self, pos=None):
1681 self.flush()
1682 if pos is None:
1683 pos = self.tell()
Antoine Pitrouca5a06a2010-01-27 21:48:46 +00001684 return self.buffer.truncate(pos)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001685
Christian Heimes1a6387e2008-03-26 12:49:49 +00001686 def seek(self, cookie, whence=0):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001687 if self.closed:
1688 raise ValueError("tell on closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001689 if not self._seekable:
1690 raise IOError("underlying stream is not seekable")
1691 if whence == 1: # seek relative to current position
1692 if cookie != 0:
1693 raise IOError("can't do nonzero cur-relative seeks")
1694 # Seeking to the current position should attempt to
1695 # sync the underlying buffer with the current position.
1696 whence = 0
1697 cookie = self.tell()
1698 if whence == 2: # seek relative to end of file
1699 if cookie != 0:
1700 raise IOError("can't do nonzero end-relative seeks")
1701 self.flush()
1702 position = self.buffer.seek(0, 2)
1703 self._set_decoded_chars('')
1704 self._snapshot = None
1705 if self._decoder:
1706 self._decoder.reset()
1707 return position
1708 if whence != 0:
1709 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1710 (whence,))
1711 if cookie < 0:
1712 raise ValueError("negative seek position %r" % (cookie,))
1713 self.flush()
1714
1715 # The strategy of seek() is to go back to the safe start point
1716 # and replay the effect of read(chars_to_skip) from there.
1717 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1718 self._unpack_cookie(cookie)
1719
1720 # Seek back to the safe start point.
1721 self.buffer.seek(start_pos)
1722 self._set_decoded_chars('')
1723 self._snapshot = None
1724
1725 # Restore the decoder to its state from the safe start point.
1726 if self._decoder or dec_flags or chars_to_skip:
1727 self._decoder = self._decoder or self._get_decoder()
1728 self._decoder.setstate((b'', dec_flags))
1729 self._snapshot = (dec_flags, b'')
1730
1731 if chars_to_skip:
1732 # Just like _read_chunk, feed the decoder and save a snapshot.
1733 input_chunk = self.buffer.read(bytes_to_feed)
1734 self._set_decoded_chars(
1735 self._decoder.decode(input_chunk, need_eof))
1736 self._snapshot = (dec_flags, input_chunk)
1737
1738 # Skip chars_to_skip of the decoded characters.
1739 if len(self._decoded_chars) < chars_to_skip:
1740 raise IOError("can't restore logical file position")
1741 self._decoded_chars_used = chars_to_skip
1742
Victor Stinner8243ddb2010-07-28 01:58:41 +00001743 # Finally, reset the encoder (merely useful for proper BOM handling)
1744 try:
1745 encoder = self._encoder or self._get_encoder()
1746 except LookupError:
1747 # Sometimes the encoder doesn't exist
1748 pass
1749 else:
1750 if cookie != 0:
1751 encoder.setstate(0)
1752 else:
1753 encoder.reset()
Christian Heimes1a6387e2008-03-26 12:49:49 +00001754 return cookie
1755
1756 def read(self, n=None):
1757 if n is None:
1758 n = -1
1759 decoder = self._decoder or self._get_decoder()
Ezio Melotti26dfaac2010-08-02 21:35:06 +00001760 try:
1761 n.__index__
1762 except AttributeError:
1763 raise TypeError("an integer is required")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001764 if n < 0:
1765 # Read everything.
1766 result = (self._get_decoded_chars() +
1767 decoder.decode(self.buffer.read(), final=True))
1768 self._set_decoded_chars('')
1769 self._snapshot = None
1770 return result
1771 else:
1772 # Keep reading chunks until we have n characters to return.
1773 eof = False
1774 result = self._get_decoded_chars(n)
1775 while len(result) < n and not eof:
1776 eof = not self._read_chunk()
1777 result += self._get_decoded_chars(n - len(result))
1778 return result
1779
1780 def next(self):
1781 self._telling = False
1782 line = self.readline()
1783 if not line:
1784 self._snapshot = None
1785 self._telling = self._seekable
1786 raise StopIteration
1787 return line
1788
1789 def readline(self, limit=None):
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001790 if self.closed:
1791 raise ValueError("read from closed file")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001792 if limit is None:
1793 limit = -1
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001794 if not isinstance(limit, (int, long)):
1795 raise TypeError("limit must be an integer")
Christian Heimes1a6387e2008-03-26 12:49:49 +00001796
1797 # Grab all the decoded text (we will rewind any extra bits later).
1798 line = self._get_decoded_chars()
1799
1800 start = 0
1801 decoder = self._decoder or self._get_decoder()
1802
1803 pos = endpos = None
1804 while True:
1805 if self._readtranslate:
1806 # Newlines are already translated, only search for \n
1807 pos = line.find('\n', start)
1808 if pos >= 0:
1809 endpos = pos + 1
1810 break
1811 else:
1812 start = len(line)
1813
1814 elif self._readuniversal:
1815 # Universal newline search. Find any of \r, \r\n, \n
1816 # The decoder ensures that \r\n are not split in two pieces
1817
1818 # In C we'd look for these in parallel of course.
1819 nlpos = line.find("\n", start)
1820 crpos = line.find("\r", start)
1821 if crpos == -1:
1822 if nlpos == -1:
1823 # Nothing found
1824 start = len(line)
1825 else:
1826 # Found \n
1827 endpos = nlpos + 1
1828 break
1829 elif nlpos == -1:
1830 # Found lone \r
1831 endpos = crpos + 1
1832 break
1833 elif nlpos < crpos:
1834 # Found \n
1835 endpos = nlpos + 1
1836 break
1837 elif nlpos == crpos + 1:
1838 # Found \r\n
1839 endpos = crpos + 2
1840 break
1841 else:
1842 # Found \r
1843 endpos = crpos + 1
1844 break
1845 else:
1846 # non-universal
1847 pos = line.find(self._readnl)
1848 if pos >= 0:
1849 endpos = pos + len(self._readnl)
1850 break
1851
1852 if limit >= 0 and len(line) >= limit:
1853 endpos = limit # reached length limit
1854 break
1855
1856 # No line ending seen yet - get more data
1857 more_line = ''
1858 while self._read_chunk():
1859 if self._decoded_chars:
1860 break
1861 if self._decoded_chars:
1862 line += self._get_decoded_chars()
1863 else:
1864 # end of file
1865 self._set_decoded_chars('')
1866 self._snapshot = None
1867 return line
1868
1869 if limit >= 0 and endpos > limit:
1870 endpos = limit # don't exceed limit
1871
1872 # Rewind _decoded_chars to just after the line ending we found.
1873 self._rewind_decoded_chars(len(line) - endpos)
1874 return line[:endpos]
1875
1876 @property
1877 def newlines(self):
1878 return self._decoder.newlines if self._decoder else None
1879
1880class StringIO(TextIOWrapper):
1881
Benjamin Peterson9ae080e2008-05-04 22:39:33 +00001882 """An in-memory stream for text. The initial_value argument sets the
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001883 value of object. The other arguments are like those of TextIOWrapper's
1884 constructor.
1885 """
Christian Heimes1a6387e2008-03-26 12:49:49 +00001886
1887 def __init__(self, initial_value="", encoding="utf-8",
1888 errors="strict", newline="\n"):
1889 super(StringIO, self).__init__(BytesIO(),
1890 encoding=encoding,
1891 errors=errors,
1892 newline=newline)
Alexandre Vassalottidd0b90a2009-06-12 21:20:23 +00001893 # Issue #5645: make universal newlines semantics the same as in the
1894 # C version, even under Windows.
1895 if newline is None:
1896 self._writetranslate = False
Christian Heimes1a6387e2008-03-26 12:49:49 +00001897 if initial_value:
1898 if not isinstance(initial_value, unicode):
1899 initial_value = unicode(initial_value)
1900 self.write(initial_value)
1901 self.seek(0)
1902
1903 def getvalue(self):
1904 self.flush()
1905 return self.buffer.getvalue().decode(self._encoding, self._errors)