blob: a7f4301cc1d69695830a46da35114f53ff673ded [file] [log] [blame]
Antoine Pitrou19690592009-06-12 20:14:08 +00001"""
2Python implementation of the io module.
3"""
4
Benjamin Petersonfed4abc2010-04-27 21:17:22 +00005from __future__ import (print_function, unicode_literals)
Antoine Pitrou19690592009-06-12 20:14:08 +00006
7import os
8import abc
9import codecs
10import warnings
Antoine Pitrou5aa7df32011-11-21 20:16:44 +010011import errno
Benjamin Peterson5e9cc5e2010-04-27 21:15:28 +000012# Import thread instead of threading to reduce startup cost
Antoine Pitrou19690592009-06-12 20:14:08 +000013try:
14 from thread import allocate_lock as Lock
15except ImportError:
16 from dummy_thread import allocate_lock as Lock
17
18import io
Benjamin Peterson27737252010-04-27 21:18:30 +000019from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Antoine Pitrou6439c002011-02-25 21:35:47 +000020from errno import EINTR
Antoine Pitrou19690592009-06-12 20:14:08 +000021
22__metaclass__ = type
23
24# open() uses st_blksize whenever we can
25DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
26
27# NOTE: Base classes defined here are registered with the "official" ABCs
Benjamin Peterson6a74a512015-03-18 21:35:38 -050028# defined in io.py. We don't use real inheritance though, because we don't want
29# to inherit the C implementations.
Antoine Pitrou19690592009-06-12 20:14:08 +000030
31
32class BlockingIOError(IOError):
33
34 """Exception raised when I/O would block on a non-blocking I/O stream."""
35
36 def __init__(self, errno, strerror, characters_written=0):
37 super(IOError, self).__init__(errno, strerror)
38 if not isinstance(characters_written, (int, long)):
39 raise TypeError("characters_written must be a integer")
40 self.characters_written = characters_written
41
42
Benjamin Petersona9bd6d52010-04-27 21:01:54 +000043def open(file, mode="r", buffering=-1,
Antoine Pitrou19690592009-06-12 20:14:08 +000044 encoding=None, errors=None,
45 newline=None, closefd=True):
46
47 r"""Open file and return a stream. Raise IOError upon failure.
48
49 file is either a text or byte string giving the name (and the path
50 if the file isn't in the current working directory) of the file to
51 be opened or an integer file descriptor of the file to be
52 wrapped. (If a file descriptor is given, it is closed when the
53 returned I/O object is closed, unless closefd is set to False.)
54
55 mode is an optional string that specifies the mode in which the file
56 is opened. It defaults to 'r' which means open for reading in text
57 mode. Other common values are 'w' for writing (truncating the file if
58 it already exists), and 'a' for appending (which on some Unix systems,
59 means that all writes append to the end of the file regardless of the
60 current seek position). In text mode, if encoding is not specified the
61 encoding used is platform dependent. (For reading and writing raw
62 bytes use binary mode and leave encoding unspecified.) The available
63 modes are:
64
65 ========= ===============================================================
66 Character Meaning
67 --------- ---------------------------------------------------------------
68 'r' open for reading (default)
69 'w' open for writing, truncating the file first
70 'a' open for writing, appending to the end of the file if it exists
71 'b' binary mode
72 't' text mode (default)
73 '+' open a disk file for updating (reading and writing)
74 'U' universal newline mode (for backwards compatibility; unneeded
75 for new code)
76 ========= ===============================================================
77
78 The default mode is 'rt' (open for reading text). For binary random
79 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
80 'r+b' opens the file without truncation.
81
82 Python distinguishes between files opened in binary and text modes,
83 even when the underlying operating system doesn't. Files opened in
84 binary mode (appending 'b' to the mode argument) return contents as
85 bytes objects without any decoding. In text mode (the default, or when
86 't' is appended to the mode argument), the contents of the file are
87 returned as strings, the bytes having been first decoded using a
88 platform-dependent encoding or using the specified encoding if given.
89
Antoine Pitroue812d292009-12-19 21:01:10 +000090 buffering is an optional integer used to set the buffering policy.
91 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
92 line buffering (only usable in text mode), and an integer > 1 to indicate
93 the size of a fixed-size chunk buffer. When no buffering argument is
94 given, the default buffering policy works as follows:
95
96 * Binary files are buffered in fixed-size chunks; the size of the buffer
97 is chosen using a heuristic trying to determine the underlying device's
98 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
99 On many systems, the buffer will typically be 4096 or 8192 bytes long.
100
101 * "Interactive" text files (files for which isatty() returns True)
102 use line buffering. Other text files use the policy described above
103 for binary files.
104
Antoine Pitrou19690592009-06-12 20:14:08 +0000105 encoding is the name of the encoding used to decode or encode the
106 file. This should only be used in text mode. The default encoding is
107 platform dependent, but any encoding supported by Python can be
108 passed. See the codecs module for the list of supported encodings.
109
110 errors is an optional string that specifies how encoding errors are to
111 be handled---this argument should not be used in binary mode. Pass
112 'strict' to raise a ValueError exception if there is an encoding error
113 (the default of None has the same effect), or pass 'ignore' to ignore
114 errors. (Note that ignoring encoding errors can lead to data loss.)
115 See the documentation for codecs.register for a list of the permitted
116 encoding error strings.
117
118 newline controls how universal newlines works (it only applies to text
119 mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
120 follows:
121
122 * On input, if newline is None, universal newlines mode is
123 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
124 these are translated into '\n' before being returned to the
125 caller. If it is '', universal newline mode is enabled, but line
126 endings are returned to the caller untranslated. If it has any of
127 the other legal values, input lines are only terminated by the given
128 string, and the line ending is returned to the caller untranslated.
129
130 * On output, if newline is None, any '\n' characters written are
131 translated to the system default line separator, os.linesep. If
132 newline is '', no translation takes place. If newline is any of the
133 other legal values, any '\n' characters written are translated to
134 the given string.
135
136 If closefd is False, the underlying file descriptor will be kept open
137 when the file is closed. This does not work when a file name is given
138 and must be True in that case.
139
140 open() returns a file object whose type depends on the mode, and
141 through which the standard file operations such as reading and writing
142 are performed. When open() is used to open a file in a text mode ('w',
143 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
144 a file in a binary mode, the returned class varies: in read binary
145 mode, it returns a BufferedReader; in write binary and append binary
146 modes, it returns a BufferedWriter, and in read/write mode, it returns
147 a BufferedRandom.
148
149 It is also possible to use a string or bytearray as a file for both
150 reading and writing. For strings StringIO can be used like a file
151 opened in a text mode, and for bytes a BytesIO can be used like a file
152 opened in a binary mode.
153 """
154 if not isinstance(file, (basestring, int, long)):
155 raise TypeError("invalid file: %r" % file)
156 if not isinstance(mode, basestring):
157 raise TypeError("invalid mode: %r" % mode)
Benjamin Petersona9bd6d52010-04-27 21:01:54 +0000158 if not isinstance(buffering, (int, long)):
Antoine Pitrou19690592009-06-12 20:14:08 +0000159 raise TypeError("invalid buffering: %r" % buffering)
160 if encoding is not None and not isinstance(encoding, basestring):
161 raise TypeError("invalid encoding: %r" % encoding)
162 if errors is not None and not isinstance(errors, basestring):
163 raise TypeError("invalid errors: %r" % errors)
164 modes = set(mode)
165 if modes - set("arwb+tU") or len(mode) > len(modes):
166 raise ValueError("invalid mode: %r" % mode)
167 reading = "r" in modes
168 writing = "w" in modes
169 appending = "a" in modes
170 updating = "+" in modes
171 text = "t" in modes
172 binary = "b" in modes
173 if "U" in modes:
174 if writing or appending:
175 raise ValueError("can't use U and writing mode at once")
176 reading = True
177 if text and binary:
178 raise ValueError("can't have text and binary mode at once")
179 if reading + writing + appending > 1:
180 raise ValueError("can't have read/write/append mode at once")
181 if not (reading or writing or appending):
182 raise ValueError("must have exactly one of read/write/append mode")
183 if binary and encoding is not None:
184 raise ValueError("binary mode doesn't take an encoding argument")
185 if binary and errors is not None:
186 raise ValueError("binary mode doesn't take an errors argument")
187 if binary and newline is not None:
188 raise ValueError("binary mode doesn't take a newline argument")
189 raw = FileIO(file,
190 (reading and "r" or "") +
191 (writing and "w" or "") +
192 (appending and "a" or "") +
193 (updating and "+" or ""),
194 closefd)
Serhiy Storchaka05b0a1b2014-06-09 13:32:08 +0300195 result = raw
196 try:
197 line_buffering = False
198 if buffering == 1 or buffering < 0 and raw.isatty():
199 buffering = -1
200 line_buffering = True
201 if buffering < 0:
202 buffering = DEFAULT_BUFFER_SIZE
203 try:
204 bs = os.fstat(raw.fileno()).st_blksize
205 except (os.error, AttributeError):
206 pass
207 else:
208 if bs > 1:
209 buffering = bs
210 if buffering < 0:
211 raise ValueError("invalid buffering size")
212 if buffering == 0:
213 if binary:
214 return result
215 raise ValueError("can't have unbuffered text I/O")
216 if updating:
217 buffer = BufferedRandom(raw, buffering)
218 elif writing or appending:
219 buffer = BufferedWriter(raw, buffering)
220 elif reading:
221 buffer = BufferedReader(raw, buffering)
Antoine Pitrou19690592009-06-12 20:14:08 +0000222 else:
Serhiy Storchaka05b0a1b2014-06-09 13:32:08 +0300223 raise ValueError("unknown mode: %r" % mode)
224 result = buffer
Antoine Pitrou19690592009-06-12 20:14:08 +0000225 if binary:
Serhiy Storchaka05b0a1b2014-06-09 13:32:08 +0300226 return result
227 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
228 result = text
229 text.mode = mode
230 return result
231 except:
232 result.close()
233 raise
Antoine Pitrou19690592009-06-12 20:14:08 +0000234
235
236class DocDescriptor:
237 """Helper for builtins.open.__doc__
238 """
239 def __get__(self, obj, typ):
240 return (
Benjamin Petersonae9f8bd2010-04-27 21:19:06 +0000241 "open(file, mode='r', buffering=-1, encoding=None, "
Antoine Pitrou19690592009-06-12 20:14:08 +0000242 "errors=None, newline=None, closefd=True)\n\n" +
243 open.__doc__)
244
245class OpenWrapper:
246 """Wrapper for builtins.open
247
248 Trick so that open won't become a bound method when stored
249 as a class variable (as dbm.dumb does).
250
251 See initstdio() in Python/pythonrun.c.
252 """
253 __doc__ = DocDescriptor()
254
255 def __new__(cls, *args, **kwargs):
256 return open(*args, **kwargs)
257
258
259class UnsupportedOperation(ValueError, IOError):
260 pass
261
262
263class IOBase:
264 __metaclass__ = abc.ABCMeta
265
266 """The abstract base class for all I/O classes, acting on streams of
267 bytes. There is no public constructor.
268
269 This class provides dummy implementations for many methods that
270 derived classes can override selectively; the default implementations
271 represent a file that cannot be read, written or seeked.
272
273 Even though IOBase does not declare read, readinto, or write because
274 their signatures will vary, implementations and clients should
275 consider those methods part of the interface. Also, implementations
276 may raise a IOError when operations they do not support are called.
277
278 The basic type used for binary data read from or written to a file is
279 bytes. bytearrays are accepted too, and in some cases (such as
280 readinto) needed. Text I/O classes work with str data.
281
282 Note that calling any method (even inquiries) on a closed stream is
283 undefined. Implementations may raise IOError in this case.
284
285 IOBase (and its subclasses) support the iterator protocol, meaning
286 that an IOBase object can be iterated over yielding the lines in a
287 stream.
288
289 IOBase also supports the :keyword:`with` statement. In this example,
290 fp is closed after the suite of the with statement is complete:
291
292 with open('spam.txt', 'r') as fp:
293 fp.write('Spam and eggs!')
294 """
295
296 ### Internal ###
297
298 def _unsupported(self, name):
299 """Internal: raise an exception for unsupported operations."""
300 raise UnsupportedOperation("%s.%s() not supported" %
301 (self.__class__.__name__, name))
302
303 ### Positioning ###
304
305 def seek(self, pos, whence=0):
306 """Change stream position.
307
Terry Jan Reedya70f60a2013-03-11 17:56:17 -0400308 Change the stream position to byte offset pos. Argument pos is
Antoine Pitrou19690592009-06-12 20:14:08 +0000309 interpreted relative to the position indicated by whence. Values
310 for whence are:
311
312 * 0 -- start of stream (the default); offset should be zero or positive
313 * 1 -- current stream position; offset may be negative
314 * 2 -- end of stream; offset is usually negative
315
316 Return the new absolute position.
317 """
318 self._unsupported("seek")
319
320 def tell(self):
321 """Return current stream position."""
322 return self.seek(0, 1)
323
324 def truncate(self, pos=None):
325 """Truncate file to size bytes.
326
327 Size defaults to the current IO position as reported by tell(). Return
328 the new size.
329 """
330 self._unsupported("truncate")
331
332 ### Flush and close ###
333
334 def flush(self):
335 """Flush write buffers, if applicable.
336
337 This is not implemented for read-only and non-blocking streams.
338 """
Antoine Pitrouf7fd8e42010-05-03 16:25:33 +0000339 self._checkClosed()
Antoine Pitrou19690592009-06-12 20:14:08 +0000340 # XXX Should this return the number of bytes written???
341
342 __closed = False
343
344 def close(self):
345 """Flush and close the IO object.
346
347 This method has no effect if the file is already closed.
348 """
349 if not self.__closed:
Benjamin Petersona2d6d712012-12-20 12:24:10 -0600350 try:
351 self.flush()
352 finally:
353 self.__closed = True
Antoine Pitrou19690592009-06-12 20:14:08 +0000354
355 def __del__(self):
356 """Destructor. Calls close()."""
357 # The try/except block is in case this is called at program
358 # exit time, when it's possible that globals have already been
359 # deleted, and then the close() call might fail. Since
360 # there's nothing we can do about such failures and they annoy
361 # the end users, we suppress the traceback.
362 try:
363 self.close()
364 except:
365 pass
366
367 ### Inquiries ###
368
369 def seekable(self):
370 """Return whether object supports random access.
371
372 If False, seek(), tell() and truncate() will raise IOError.
373 This method may need to do a test seek().
374 """
375 return False
376
377 def _checkSeekable(self, msg=None):
378 """Internal: raise an IOError if file is not seekable
379 """
380 if not self.seekable():
381 raise IOError("File or stream is not seekable."
382 if msg is None else msg)
383
384
385 def readable(self):
386 """Return whether object was opened for reading.
387
388 If False, read() will raise IOError.
389 """
390 return False
391
392 def _checkReadable(self, msg=None):
393 """Internal: raise an IOError if file is not readable
394 """
395 if not self.readable():
396 raise IOError("File or stream is not readable."
397 if msg is None else msg)
398
399 def writable(self):
400 """Return whether object was opened for writing.
401
402 If False, write() and truncate() will raise IOError.
403 """
404 return False
405
406 def _checkWritable(self, msg=None):
407 """Internal: raise an IOError if file is not writable
408 """
409 if not self.writable():
410 raise IOError("File or stream is not writable."
411 if msg is None else msg)
412
413 @property
414 def closed(self):
415 """closed: bool. True iff the file has been closed.
416
417 For backwards compatibility, this is a property, not a predicate.
418 """
419 return self.__closed
420
421 def _checkClosed(self, msg=None):
422 """Internal: raise an ValueError if file is closed
423 """
424 if self.closed:
425 raise ValueError("I/O operation on closed file."
426 if msg is None else msg)
427
428 ### Context manager ###
429
430 def __enter__(self):
431 """Context management protocol. Returns self."""
432 self._checkClosed()
433 return self
434
435 def __exit__(self, *args):
436 """Context management protocol. Calls close()"""
437 self.close()
438
439 ### Lower-level APIs ###
440
441 # XXX Should these be present even if unimplemented?
442
443 def fileno(self):
444 """Returns underlying file descriptor if one exists.
445
446 An IOError is raised if the IO object does not use a file descriptor.
447 """
448 self._unsupported("fileno")
449
450 def isatty(self):
451 """Return whether this is an 'interactive' stream.
452
453 Return False if it can't be determined.
454 """
455 self._checkClosed()
456 return False
457
458 ### Readline[s] and writelines ###
459
460 def readline(self, limit=-1):
461 r"""Read and return a line from the stream.
462
463 If limit is specified, at most limit bytes will be read.
464
465 The line terminator is always b'\n' for binary files; for text
466 files, the newlines argument to open can be used to select the line
467 terminator(s) recognized.
468 """
469 # For backwards compatibility, a (slowish) readline().
470 if hasattr(self, "peek"):
471 def nreadahead():
472 readahead = self.peek(1)
473 if not readahead:
474 return 1
475 n = (readahead.find(b"\n") + 1) or len(readahead)
476 if limit >= 0:
477 n = min(n, limit)
478 return n
479 else:
480 def nreadahead():
481 return 1
482 if limit is None:
483 limit = -1
484 elif not isinstance(limit, (int, long)):
485 raise TypeError("limit must be an integer")
486 res = bytearray()
487 while limit < 0 or len(res) < limit:
488 b = self.read(nreadahead())
489 if not b:
490 break
491 res += b
492 if res.endswith(b"\n"):
493 break
494 return bytes(res)
495
496 def __iter__(self):
497 self._checkClosed()
498 return self
499
500 def next(self):
501 line = self.readline()
502 if not line:
503 raise StopIteration
504 return line
505
506 def readlines(self, hint=None):
507 """Return a list of lines from the stream.
508
509 hint can be specified to control the number of lines read: no more
510 lines will be read if the total size (in bytes/characters) of all
511 lines so far exceeds hint.
512 """
513 if hint is not None and not isinstance(hint, (int, long)):
514 raise TypeError("integer or None expected")
515 if hint is None or hint <= 0:
516 return list(self)
517 n = 0
518 lines = []
519 for line in self:
520 lines.append(line)
521 n += len(line)
522 if n >= hint:
523 break
524 return lines
525
526 def writelines(self, lines):
527 self._checkClosed()
528 for line in lines:
529 self.write(line)
530
531io.IOBase.register(IOBase)
532
533
534class RawIOBase(IOBase):
535
536 """Base class for raw binary I/O."""
537
538 # The read() method is implemented by calling readinto(); derived
539 # classes that want to support read() only need to implement
540 # readinto() as a primitive operation. In general, readinto() can be
541 # more efficient than read().
542
543 # (It would be tempting to also provide an implementation of
544 # readinto() in terms of read(), in case the latter is a more suitable
545 # primitive operation, but that would lead to nasty recursion in case
546 # a subclass doesn't implement either.)
547
548 def read(self, n=-1):
549 """Read and return up to n bytes.
550
551 Returns an empty bytes object on EOF, or None if the object is
552 set not to block and has no data to read.
553 """
554 if n is None:
555 n = -1
556 if n < 0:
557 return self.readall()
558 b = bytearray(n.__index__())
559 n = self.readinto(b)
Antoine Pitrou6391b342010-09-14 18:48:19 +0000560 if n is None:
561 return None
Antoine Pitrou19690592009-06-12 20:14:08 +0000562 del b[n:]
563 return bytes(b)
564
565 def readall(self):
566 """Read until EOF, using multiple read() call."""
567 res = bytearray()
568 while True:
569 data = self.read(DEFAULT_BUFFER_SIZE)
570 if not data:
571 break
572 res += data
Victor Stinnerdaf17e92011-05-25 22:52:37 +0200573 if res:
574 return bytes(res)
575 else:
576 # b'' or None
577 return data
Antoine Pitrou19690592009-06-12 20:14:08 +0000578
579 def readinto(self, b):
580 """Read up to len(b) bytes into b.
581
582 Returns number of bytes read (0 for EOF), or None if the object
Antoine Pitrou6391b342010-09-14 18:48:19 +0000583 is set not to block and has no data to read.
Antoine Pitrou19690592009-06-12 20:14:08 +0000584 """
585 self._unsupported("readinto")
586
587 def write(self, b):
588 """Write the given buffer to the IO stream.
589
590 Returns the number of bytes written, which may be less than len(b).
591 """
592 self._unsupported("write")
593
594io.RawIOBase.register(RawIOBase)
595from _io import FileIO
596RawIOBase.register(FileIO)
597
598
599class BufferedIOBase(IOBase):
600
601 """Base class for buffered IO objects.
602
603 The main difference with RawIOBase is that the read() method
604 supports omitting the size argument, and does not have a default
605 implementation that defers to readinto().
606
607 In addition, read(), readinto() and write() may raise
608 BlockingIOError if the underlying raw stream is in non-blocking
609 mode and not ready; unlike their raw counterparts, they will never
610 return None.
611
612 A typical implementation should not inherit from a RawIOBase
613 implementation, but wrap one.
614 """
615
616 def read(self, n=None):
617 """Read and return up to n bytes.
618
619 If the argument is omitted, None, or negative, reads and
620 returns all data until EOF.
621
622 If the argument is positive, and the underlying raw stream is
623 not 'interactive', multiple raw reads may be issued to satisfy
624 the byte count (unless EOF is reached first). But for
625 interactive raw streams (XXX and for pipes?), at most one raw
626 read will be issued, and a short result does not imply that
627 EOF is imminent.
628
629 Returns an empty bytes array on EOF.
630
631 Raises BlockingIOError if the underlying raw stream has no
632 data at the moment.
633 """
634 self._unsupported("read")
635
636 def read1(self, n=None):
637 """Read up to n bytes with at most one read() system call."""
638 self._unsupported("read1")
639
640 def readinto(self, b):
641 """Read up to len(b) bytes into b.
642
643 Like read(), this may issue multiple reads to the underlying raw
644 stream, unless the latter is 'interactive'.
645
646 Returns the number of bytes read (0 for EOF).
647
648 Raises BlockingIOError if the underlying raw stream has no
649 data at the moment.
650 """
651 # XXX This ought to work with anything that supports the buffer API
652 data = self.read(len(b))
653 n = len(data)
654 try:
655 b[:n] = data
656 except TypeError as err:
657 import array
658 if not isinstance(b, array.array):
659 raise err
660 b[:n] = array.array(b'b', data)
661 return n
662
663 def write(self, b):
664 """Write the given buffer to the IO stream.
665
666 Return the number of bytes written, which is never less than
667 len(b).
668
669 Raises BlockingIOError if the buffer is full and the
670 underlying raw stream cannot accept more data at the moment.
671 """
672 self._unsupported("write")
673
674 def detach(self):
675 """
676 Separate the underlying raw stream from the buffer and return it.
677
678 After the raw stream has been detached, the buffer is in an unusable
679 state.
680 """
681 self._unsupported("detach")
682
683io.BufferedIOBase.register(BufferedIOBase)
684
685
686class _BufferedIOMixin(BufferedIOBase):
687
688 """A mixin implementation of BufferedIOBase with an underlying raw stream.
689
690 This passes most requests on to the underlying raw stream. It
691 does *not* provide implementations of read(), readinto() or
692 write().
693 """
694
695 def __init__(self, raw):
Antoine Pitroufc9ead62010-12-21 21:26:55 +0000696 self._raw = raw
Antoine Pitrou19690592009-06-12 20:14:08 +0000697
698 ### Positioning ###
699
700 def seek(self, pos, whence=0):
701 new_position = self.raw.seek(pos, whence)
702 if new_position < 0:
703 raise IOError("seek() returned an invalid position")
704 return new_position
705
706 def tell(self):
707 pos = self.raw.tell()
708 if pos < 0:
709 raise IOError("tell() returned an invalid position")
710 return pos
711
712 def truncate(self, pos=None):
713 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
714 # and a flush may be necessary to synch both views of the current
715 # file state.
716 self.flush()
717
718 if pos is None:
719 pos = self.tell()
720 # XXX: Should seek() be used, instead of passing the position
721 # XXX directly to truncate?
722 return self.raw.truncate(pos)
723
724 ### Flush and close ###
725
726 def flush(self):
Antoine Pitrouf7fd8e42010-05-03 16:25:33 +0000727 if self.closed:
728 raise ValueError("flush of closed file")
Antoine Pitrou19690592009-06-12 20:14:08 +0000729 self.raw.flush()
730
731 def close(self):
Antoine Pitrouf7fd8e42010-05-03 16:25:33 +0000732 if self.raw is not None and not self.closed:
Antoine Pitrou5aa7df32011-11-21 20:16:44 +0100733 try:
734 # may raise BlockingIOError or BrokenPipeError etc
735 self.flush()
736 finally:
737 self.raw.close()
Antoine Pitrou19690592009-06-12 20:14:08 +0000738
739 def detach(self):
740 if self.raw is None:
741 raise ValueError("raw stream already detached")
742 self.flush()
Antoine Pitroufc9ead62010-12-21 21:26:55 +0000743 raw = self._raw
744 self._raw = None
Antoine Pitrou19690592009-06-12 20:14:08 +0000745 return raw
746
747 ### Inquiries ###
748
749 def seekable(self):
750 return self.raw.seekable()
751
752 def readable(self):
753 return self.raw.readable()
754
755 def writable(self):
756 return self.raw.writable()
757
758 @property
Antoine Pitroufc9ead62010-12-21 21:26:55 +0000759 def raw(self):
760 return self._raw
761
762 @property
Antoine Pitrou19690592009-06-12 20:14:08 +0000763 def closed(self):
764 return self.raw.closed
765
766 @property
767 def name(self):
768 return self.raw.name
769
770 @property
771 def mode(self):
772 return self.raw.mode
773
774 def __repr__(self):
775 clsname = self.__class__.__name__
776 try:
777 name = self.name
Benjamin Peterson53ae6142014-12-21 20:51:50 -0600778 except Exception:
Antoine Pitrou19690592009-06-12 20:14:08 +0000779 return "<_pyio.{0}>".format(clsname)
780 else:
781 return "<_pyio.{0} name={1!r}>".format(clsname, name)
782
783 ### Lower-level APIs ###
784
785 def fileno(self):
786 return self.raw.fileno()
787
788 def isatty(self):
789 return self.raw.isatty()
790
791
792class BytesIO(BufferedIOBase):
793
794 """Buffered I/O implementation using an in-memory bytes buffer."""
795
796 def __init__(self, initial_bytes=None):
797 buf = bytearray()
798 if initial_bytes is not None:
799 buf.extend(initial_bytes)
800 self._buffer = buf
801 self._pos = 0
802
Antoine Pitroufa94e802009-10-24 12:23:18 +0000803 def __getstate__(self):
804 if self.closed:
805 raise ValueError("__getstate__ on closed file")
806 return self.__dict__.copy()
807
Antoine Pitrou19690592009-06-12 20:14:08 +0000808 def getvalue(self):
809 """Return the bytes value (contents) of the buffer
810 """
811 if self.closed:
812 raise ValueError("getvalue on closed file")
813 return bytes(self._buffer)
814
815 def read(self, n=None):
816 if self.closed:
817 raise ValueError("read from closed file")
818 if n is None:
819 n = -1
820 if not isinstance(n, (int, long)):
821 raise TypeError("integer argument expected, got {0!r}".format(
822 type(n)))
823 if n < 0:
824 n = len(self._buffer)
825 if len(self._buffer) <= self._pos:
826 return b""
827 newpos = min(len(self._buffer), self._pos + n)
828 b = self._buffer[self._pos : newpos]
829 self._pos = newpos
830 return bytes(b)
831
832 def read1(self, n):
833 """This is the same as read.
834 """
835 return self.read(n)
836
837 def write(self, b):
838 if self.closed:
839 raise ValueError("write to closed file")
840 if isinstance(b, unicode):
841 raise TypeError("can't write unicode to binary stream")
842 n = len(b)
843 if n == 0:
844 return 0
845 pos = self._pos
846 if pos > len(self._buffer):
847 # Inserts null bytes between the current end of the file
848 # and the new write position.
849 padding = b'\x00' * (pos - len(self._buffer))
850 self._buffer += padding
851 self._buffer[pos:pos + n] = b
852 self._pos += n
853 return n
854
855 def seek(self, pos, whence=0):
856 if self.closed:
857 raise ValueError("seek on closed file")
858 try:
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000859 pos.__index__
860 except AttributeError:
Antoine Pitrou19690592009-06-12 20:14:08 +0000861 raise TypeError("an integer is required")
862 if whence == 0:
863 if pos < 0:
864 raise ValueError("negative seek position %r" % (pos,))
865 self._pos = pos
866 elif whence == 1:
867 self._pos = max(0, self._pos + pos)
868 elif whence == 2:
869 self._pos = max(0, len(self._buffer) + pos)
870 else:
871 raise ValueError("invalid whence value")
872 return self._pos
873
874 def tell(self):
875 if self.closed:
876 raise ValueError("tell on closed file")
877 return self._pos
878
879 def truncate(self, pos=None):
880 if self.closed:
881 raise ValueError("truncate on closed file")
882 if pos is None:
883 pos = self._pos
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000884 else:
885 try:
886 pos.__index__
887 except AttributeError:
888 raise TypeError("an integer is required")
889 if pos < 0:
890 raise ValueError("negative truncate position %r" % (pos,))
Antoine Pitrou19690592009-06-12 20:14:08 +0000891 del self._buffer[pos:]
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000892 return pos
Antoine Pitrou19690592009-06-12 20:14:08 +0000893
894 def readable(self):
Antoine Pitrouc5eec0e2012-09-05 20:11:49 +0200895 if self.closed:
896 raise ValueError("I/O operation on closed file.")
Antoine Pitrou19690592009-06-12 20:14:08 +0000897 return True
898
899 def writable(self):
Antoine Pitrouc5eec0e2012-09-05 20:11:49 +0200900 if self.closed:
901 raise ValueError("I/O operation on closed file.")
Antoine Pitrou19690592009-06-12 20:14:08 +0000902 return True
903
904 def seekable(self):
Antoine Pitrouc5eec0e2012-09-05 20:11:49 +0200905 if self.closed:
906 raise ValueError("I/O operation on closed file.")
Antoine Pitrou19690592009-06-12 20:14:08 +0000907 return True
908
909
910class BufferedReader(_BufferedIOMixin):
911
912 """BufferedReader(raw[, buffer_size])
913
914 A buffer for a readable, sequential BaseRawIO object.
915
916 The constructor creates a BufferedReader for the given readable raw
917 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
918 is used.
919 """
920
921 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
922 """Create a new buffered reader using the given readable raw IO object.
923 """
924 if not raw.readable():
925 raise IOError('"raw" argument must be readable.')
926
927 _BufferedIOMixin.__init__(self, raw)
928 if buffer_size <= 0:
929 raise ValueError("invalid buffer size")
930 self.buffer_size = buffer_size
931 self._reset_read_buf()
932 self._read_lock = Lock()
933
934 def _reset_read_buf(self):
935 self._read_buf = b""
936 self._read_pos = 0
937
938 def read(self, n=None):
939 """Read n bytes.
940
941 Returns exactly n bytes of data unless the underlying raw IO
942 stream reaches EOF or if the call would block in non-blocking
943 mode. If n is negative, read until EOF or until read() would
944 block.
945 """
946 if n is not None and n < -1:
947 raise ValueError("invalid number of bytes to read")
948 with self._read_lock:
949 return self._read_unlocked(n)
950
951 def _read_unlocked(self, n=None):
952 nodata_val = b""
953 empty_values = (b"", None)
954 buf = self._read_buf
955 pos = self._read_pos
956
957 # Special case for when the number of bytes to read is unspecified.
958 if n is None or n == -1:
959 self._reset_read_buf()
960 chunks = [buf[pos:]] # Strip the consumed bytes.
961 current_size = 0
962 while True:
963 # Read until EOF or until read() would block.
Antoine Pitrou6439c002011-02-25 21:35:47 +0000964 try:
965 chunk = self.raw.read()
966 except IOError as e:
967 if e.errno != EINTR:
968 raise
969 continue
Antoine Pitrou19690592009-06-12 20:14:08 +0000970 if chunk in empty_values:
971 nodata_val = chunk
972 break
973 current_size += len(chunk)
974 chunks.append(chunk)
975 return b"".join(chunks) or nodata_val
976
977 # The number of bytes to read is specified, return at most n bytes.
978 avail = len(buf) - pos # Length of the available buffered data.
979 if n <= avail:
980 # Fast path: the data to read is fully buffered.
981 self._read_pos += n
982 return buf[pos:pos+n]
983 # Slow path: read from the stream until enough bytes are read,
984 # or until an EOF occurs or until read() would block.
985 chunks = [buf[pos:]]
986 wanted = max(self.buffer_size, n)
987 while avail < n:
Antoine Pitrou6439c002011-02-25 21:35:47 +0000988 try:
989 chunk = self.raw.read(wanted)
990 except IOError as e:
991 if e.errno != EINTR:
992 raise
993 continue
Antoine Pitrou19690592009-06-12 20:14:08 +0000994 if chunk in empty_values:
995 nodata_val = chunk
996 break
997 avail += len(chunk)
998 chunks.append(chunk)
999 # n is more then avail only when an EOF occurred or when
1000 # read() would have blocked.
1001 n = min(n, avail)
1002 out = b"".join(chunks)
1003 self._read_buf = out[n:] # Save the extra data in the buffer.
1004 self._read_pos = 0
1005 return out[:n] if out else nodata_val
1006
1007 def peek(self, n=0):
1008 """Returns buffered bytes without advancing the position.
1009
1010 The argument indicates a desired minimal number of bytes; we
1011 do at most one raw read to satisfy it. We never return more
1012 than self.buffer_size.
1013 """
1014 with self._read_lock:
1015 return self._peek_unlocked(n)
1016
1017 def _peek_unlocked(self, n=0):
1018 want = min(n, self.buffer_size)
1019 have = len(self._read_buf) - self._read_pos
1020 if have < want or have <= 0:
1021 to_read = self.buffer_size - have
Antoine Pitrou6439c002011-02-25 21:35:47 +00001022 while True:
1023 try:
1024 current = self.raw.read(to_read)
1025 except IOError as e:
1026 if e.errno != EINTR:
1027 raise
1028 continue
1029 break
Antoine Pitrou19690592009-06-12 20:14:08 +00001030 if current:
1031 self._read_buf = self._read_buf[self._read_pos:] + current
1032 self._read_pos = 0
1033 return self._read_buf[self._read_pos:]
1034
1035 def read1(self, n):
1036 """Reads up to n bytes, with at most one read() system call."""
1037 # Returns up to n bytes. If at least one byte is buffered, we
1038 # only return buffered bytes. Otherwise, we do one raw read.
1039 if n < 0:
1040 raise ValueError("number of bytes to read must be positive")
1041 if n == 0:
1042 return b""
1043 with self._read_lock:
1044 self._peek_unlocked(1)
1045 return self._read_unlocked(
1046 min(n, len(self._read_buf) - self._read_pos))
1047
1048 def tell(self):
1049 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1050
1051 def seek(self, pos, whence=0):
1052 if not (0 <= whence <= 2):
1053 raise ValueError("invalid whence value")
1054 with self._read_lock:
1055 if whence == 1:
1056 pos -= len(self._read_buf) - self._read_pos
1057 pos = _BufferedIOMixin.seek(self, pos, whence)
1058 self._reset_read_buf()
1059 return pos
1060
1061class BufferedWriter(_BufferedIOMixin):
1062
1063 """A buffer for a writeable sequential RawIO object.
1064
1065 The constructor creates a BufferedWriter for the given writeable raw
1066 stream. If the buffer_size is not given, it defaults to
1067 DEFAULT_BUFFER_SIZE.
1068 """
1069
1070 _warning_stack_offset = 2
1071
1072 def __init__(self, raw,
1073 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1074 if not raw.writable():
1075 raise IOError('"raw" argument must be writable.')
1076
1077 _BufferedIOMixin.__init__(self, raw)
1078 if buffer_size <= 0:
1079 raise ValueError("invalid buffer size")
1080 if max_buffer_size is not None:
1081 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1082 self._warning_stack_offset)
1083 self.buffer_size = buffer_size
1084 self._write_buf = bytearray()
1085 self._write_lock = Lock()
1086
1087 def write(self, b):
1088 if self.closed:
1089 raise ValueError("write to closed file")
1090 if isinstance(b, unicode):
1091 raise TypeError("can't write unicode to binary stream")
1092 with self._write_lock:
1093 # XXX we can implement some more tricks to try and avoid
1094 # partial writes
1095 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou5aa7df32011-11-21 20:16:44 +01001096 # We're full, so let's pre-flush the buffer. (This may
1097 # raise BlockingIOError with characters_written == 0.)
1098 self._flush_unlocked()
Antoine Pitrou19690592009-06-12 20:14:08 +00001099 before = len(self._write_buf)
1100 self._write_buf.extend(b)
1101 written = len(self._write_buf) - before
1102 if len(self._write_buf) > self.buffer_size:
1103 try:
1104 self._flush_unlocked()
1105 except BlockingIOError as e:
1106 if len(self._write_buf) > self.buffer_size:
1107 # We've hit the buffer_size. We have to accept a partial
1108 # write and cut back our buffer.
1109 overage = len(self._write_buf) - self.buffer_size
1110 written -= overage
1111 self._write_buf = self._write_buf[:self.buffer_size]
1112 raise BlockingIOError(e.errno, e.strerror, written)
1113 return written
1114
1115 def truncate(self, pos=None):
1116 with self._write_lock:
1117 self._flush_unlocked()
1118 if pos is None:
1119 pos = self.raw.tell()
1120 return self.raw.truncate(pos)
1121
1122 def flush(self):
1123 with self._write_lock:
1124 self._flush_unlocked()
1125
1126 def _flush_unlocked(self):
1127 if self.closed:
1128 raise ValueError("flush of closed file")
Antoine Pitrou5aa7df32011-11-21 20:16:44 +01001129 while self._write_buf:
1130 try:
1131 n = self.raw.write(self._write_buf)
1132 except BlockingIOError:
1133 raise RuntimeError("self.raw should implement RawIOBase: it "
1134 "should not raise BlockingIOError")
1135 except IOError as e:
1136 if e.errno != EINTR:
1137 raise
1138 continue
1139 if n is None:
1140 raise BlockingIOError(
1141 errno.EAGAIN,
1142 "write could not complete without blocking", 0)
1143 if n > len(self._write_buf) or n < 0:
1144 raise IOError("write() returned incorrect number of bytes")
Antoine Pitrou19690592009-06-12 20:14:08 +00001145 del self._write_buf[:n]
Antoine Pitrou19690592009-06-12 20:14:08 +00001146
1147 def tell(self):
1148 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1149
1150 def seek(self, pos, whence=0):
1151 if not (0 <= whence <= 2):
1152 raise ValueError("invalid whence")
1153 with self._write_lock:
1154 self._flush_unlocked()
1155 return _BufferedIOMixin.seek(self, pos, whence)
1156
1157
1158class BufferedRWPair(BufferedIOBase):
1159
1160 """A buffered reader and writer object together.
1161
1162 A buffered reader object and buffered writer object put together to
1163 form a sequential IO object that can read and write. This is typically
1164 used with a socket or two-way pipe.
1165
1166 reader and writer are RawIOBase objects that are readable and
1167 writeable respectively. If the buffer_size is omitted it defaults to
1168 DEFAULT_BUFFER_SIZE.
1169 """
1170
1171 # XXX The usefulness of this (compared to having two separate IO
1172 # objects) is questionable.
1173
1174 def __init__(self, reader, writer,
1175 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1176 """Constructor.
1177
1178 The arguments are two RawIO instances.
1179 """
1180 if max_buffer_size is not None:
1181 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
1182
1183 if not reader.readable():
1184 raise IOError('"reader" argument must be readable.')
1185
1186 if not writer.writable():
1187 raise IOError('"writer" argument must be writable.')
1188
1189 self.reader = BufferedReader(reader, buffer_size)
1190 self.writer = BufferedWriter(writer, buffer_size)
1191
1192 def read(self, n=None):
1193 if n is None:
1194 n = -1
1195 return self.reader.read(n)
1196
1197 def readinto(self, b):
1198 return self.reader.readinto(b)
1199
1200 def write(self, b):
1201 return self.writer.write(b)
1202
1203 def peek(self, n=0):
1204 return self.reader.peek(n)
1205
1206 def read1(self, n):
1207 return self.reader.read1(n)
1208
1209 def readable(self):
1210 return self.reader.readable()
1211
1212 def writable(self):
1213 return self.writer.writable()
1214
1215 def flush(self):
1216 return self.writer.flush()
1217
1218 def close(self):
Serhiy Storchakaf95a57f2015-03-24 23:23:42 +02001219 try:
1220 self.writer.close()
1221 finally:
1222 self.reader.close()
Antoine Pitrou19690592009-06-12 20:14:08 +00001223
1224 def isatty(self):
1225 return self.reader.isatty() or self.writer.isatty()
1226
1227 @property
1228 def closed(self):
1229 return self.writer.closed
1230
1231
1232class BufferedRandom(BufferedWriter, BufferedReader):
1233
1234 """A buffered interface to random access streams.
1235
1236 The constructor creates a reader and writer for a seekable stream,
1237 raw, given in the first argument. If the buffer_size is omitted it
1238 defaults to DEFAULT_BUFFER_SIZE.
1239 """
1240
1241 _warning_stack_offset = 3
1242
1243 def __init__(self, raw,
1244 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1245 raw._checkSeekable()
1246 BufferedReader.__init__(self, raw, buffer_size)
1247 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1248
1249 def seek(self, pos, whence=0):
1250 if not (0 <= whence <= 2):
1251 raise ValueError("invalid whence")
1252 self.flush()
1253 if self._read_buf:
1254 # Undo read ahead.
1255 with self._read_lock:
1256 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1257 # First do the raw seek, then empty the read buffer, so that
1258 # if the raw seek fails, we don't lose buffered data forever.
1259 pos = self.raw.seek(pos, whence)
1260 with self._read_lock:
1261 self._reset_read_buf()
1262 if pos < 0:
1263 raise IOError("seek() returned invalid position")
1264 return pos
1265
1266 def tell(self):
1267 if self._write_buf:
1268 return BufferedWriter.tell(self)
1269 else:
1270 return BufferedReader.tell(self)
1271
1272 def truncate(self, pos=None):
1273 if pos is None:
1274 pos = self.tell()
1275 # Use seek to flush the read buffer.
Antoine Pitrouf3fa0742010-01-31 22:26:04 +00001276 return BufferedWriter.truncate(self, pos)
Antoine Pitrou19690592009-06-12 20:14:08 +00001277
1278 def read(self, n=None):
1279 if n is None:
1280 n = -1
1281 self.flush()
1282 return BufferedReader.read(self, n)
1283
1284 def readinto(self, b):
1285 self.flush()
1286 return BufferedReader.readinto(self, b)
1287
1288 def peek(self, n=0):
1289 self.flush()
1290 return BufferedReader.peek(self, n)
1291
1292 def read1(self, n):
1293 self.flush()
1294 return BufferedReader.read1(self, n)
1295
1296 def write(self, b):
1297 if self._read_buf:
1298 # Undo readahead
1299 with self._read_lock:
1300 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1301 self._reset_read_buf()
1302 return BufferedWriter.write(self, b)
1303
1304
1305class TextIOBase(IOBase):
1306
1307 """Base class for text I/O.
1308
1309 This class provides a character and line based interface to stream
1310 I/O. There is no readinto method because Python's character strings
1311 are immutable. There is no public constructor.
1312 """
1313
1314 def read(self, n=-1):
1315 """Read at most n characters from stream.
1316
1317 Read from underlying buffer until we have n characters or we hit EOF.
1318 If n is negative or omitted, read until EOF.
1319 """
1320 self._unsupported("read")
1321
1322 def write(self, s):
1323 """Write string s to stream."""
1324 self._unsupported("write")
1325
1326 def truncate(self, pos=None):
1327 """Truncate size to pos."""
1328 self._unsupported("truncate")
1329
1330 def readline(self):
1331 """Read until newline or EOF.
1332
1333 Returns an empty string if EOF is hit immediately.
1334 """
1335 self._unsupported("readline")
1336
1337 def detach(self):
1338 """
1339 Separate the underlying buffer from the TextIOBase and return it.
1340
1341 After the underlying buffer has been detached, the TextIO is in an
1342 unusable state.
1343 """
1344 self._unsupported("detach")
1345
1346 @property
1347 def encoding(self):
1348 """Subclasses should override."""
1349 return None
1350
1351 @property
1352 def newlines(self):
1353 """Line endings translated so far.
1354
1355 Only line endings translated during reading are considered.
1356
1357 Subclasses should override.
1358 """
1359 return None
1360
1361 @property
1362 def errors(self):
1363 """Error setting of the decoder or encoder.
1364
1365 Subclasses should override."""
1366 return None
1367
1368io.TextIOBase.register(TextIOBase)
1369
1370
1371class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1372 r"""Codec used when reading a file in universal newlines mode. It wraps
1373 another incremental decoder, translating \r\n and \r into \n. It also
1374 records the types of newlines encountered. When used with
1375 translate=False, it ensures that the newline sequence is returned in
1376 one piece.
1377 """
1378 def __init__(self, decoder, translate, errors='strict'):
1379 codecs.IncrementalDecoder.__init__(self, errors=errors)
1380 self.translate = translate
1381 self.decoder = decoder
1382 self.seennl = 0
1383 self.pendingcr = False
1384
1385 def decode(self, input, final=False):
1386 # decode input (with the eventual \r from a previous pass)
1387 if self.decoder is None:
1388 output = input
1389 else:
1390 output = self.decoder.decode(input, final=final)
1391 if self.pendingcr and (output or final):
1392 output = "\r" + output
1393 self.pendingcr = False
1394
1395 # retain last \r even when not translating data:
1396 # then readline() is sure to get \r\n in one pass
1397 if output.endswith("\r") and not final:
1398 output = output[:-1]
1399 self.pendingcr = True
1400
1401 # Record which newlines are read
1402 crlf = output.count('\r\n')
1403 cr = output.count('\r') - crlf
1404 lf = output.count('\n') - crlf
1405 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1406 | (crlf and self._CRLF)
1407
1408 if self.translate:
1409 if crlf:
1410 output = output.replace("\r\n", "\n")
1411 if cr:
1412 output = output.replace("\r", "\n")
1413
1414 return output
1415
1416 def getstate(self):
1417 if self.decoder is None:
1418 buf = b""
1419 flag = 0
1420 else:
1421 buf, flag = self.decoder.getstate()
1422 flag <<= 1
1423 if self.pendingcr:
1424 flag |= 1
1425 return buf, flag
1426
1427 def setstate(self, state):
1428 buf, flag = state
1429 self.pendingcr = bool(flag & 1)
1430 if self.decoder is not None:
1431 self.decoder.setstate((buf, flag >> 1))
1432
1433 def reset(self):
1434 self.seennl = 0
1435 self.pendingcr = False
1436 if self.decoder is not None:
1437 self.decoder.reset()
1438
1439 _LF = 1
1440 _CR = 2
1441 _CRLF = 4
1442
1443 @property
1444 def newlines(self):
1445 return (None,
1446 "\n",
1447 "\r",
1448 ("\r", "\n"),
1449 "\r\n",
1450 ("\n", "\r\n"),
1451 ("\r", "\r\n"),
1452 ("\r", "\n", "\r\n")
1453 )[self.seennl]
1454
1455
1456class TextIOWrapper(TextIOBase):
1457
1458 r"""Character and line based layer over a BufferedIOBase object, buffer.
1459
1460 encoding gives the name of the encoding that the stream will be
1461 decoded or encoded with. It defaults to locale.getpreferredencoding.
1462
1463 errors determines the strictness of encoding and decoding (see the
1464 codecs.register) and defaults to "strict".
1465
1466 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1467 handling of line endings. If it is None, universal newlines is
1468 enabled. With this enabled, on input, the lines endings '\n', '\r',
1469 or '\r\n' are translated to '\n' before being returned to the
1470 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo7f4b3be2012-02-26 01:41:39 +01001471 default line separator, os.linesep. If newline is any other of its
Antoine Pitrou19690592009-06-12 20:14:08 +00001472 legal values, that newline becomes the newline when the file is read
1473 and it is returned untranslated. On output, '\n' is converted to the
1474 newline.
1475
1476 If line_buffering is True, a call to flush is implied when a call to
1477 write contains a newline character.
1478 """
1479
1480 _CHUNK_SIZE = 2048
1481
1482 def __init__(self, buffer, encoding=None, errors=None, newline=None,
1483 line_buffering=False):
1484 if newline is not None and not isinstance(newline, basestring):
1485 raise TypeError("illegal newline type: %r" % (type(newline),))
1486 if newline not in (None, "", "\n", "\r", "\r\n"):
1487 raise ValueError("illegal newline value: %r" % (newline,))
1488 if encoding is None:
1489 try:
Victor Stinner71202192010-05-04 11:35:36 +00001490 import locale
1491 except ImportError:
1492 # Importing locale may fail if Python is being built
1493 encoding = "ascii"
1494 else:
1495 encoding = locale.getpreferredencoding()
Antoine Pitrou19690592009-06-12 20:14:08 +00001496
1497 if not isinstance(encoding, basestring):
1498 raise ValueError("invalid encoding: %r" % encoding)
1499
1500 if errors is None:
1501 errors = "strict"
1502 else:
1503 if not isinstance(errors, basestring):
1504 raise ValueError("invalid errors: %r" % errors)
1505
Antoine Pitroufc9ead62010-12-21 21:26:55 +00001506 self._buffer = buffer
Antoine Pitrou19690592009-06-12 20:14:08 +00001507 self._line_buffering = line_buffering
1508 self._encoding = encoding
1509 self._errors = errors
1510 self._readuniversal = not newline
1511 self._readtranslate = newline is None
1512 self._readnl = newline
1513 self._writetranslate = newline != ''
1514 self._writenl = newline or os.linesep
1515 self._encoder = None
1516 self._decoder = None
1517 self._decoded_chars = '' # buffer for text returned from decoder
1518 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1519 self._snapshot = None # info for reconstructing decoder state
1520 self._seekable = self._telling = self.buffer.seekable()
1521
1522 if self._seekable and self.writable():
1523 position = self.buffer.tell()
1524 if position != 0:
1525 try:
1526 self._get_encoder().setstate(0)
1527 except LookupError:
1528 # Sometimes the encoder doesn't exist
1529 pass
1530
1531 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1532 # where dec_flags is the second (integer) item of the decoder state
1533 # and next_input is the chunk of input bytes that comes next after the
1534 # snapshot point. We use this to reconstruct decoder states in tell().
1535
1536 # Naming convention:
1537 # - "bytes_..." for integer variables that count input bytes
1538 # - "chars_..." for integer variables that count decoded characters
1539
1540 def __repr__(self):
1541 try:
1542 name = self.name
Benjamin Peterson53ae6142014-12-21 20:51:50 -06001543 except Exception:
Antoine Pitrou19690592009-06-12 20:14:08 +00001544 return "<_pyio.TextIOWrapper encoding='{0}'>".format(self.encoding)
1545 else:
1546 return "<_pyio.TextIOWrapper name={0!r} encoding='{1}'>".format(
1547 name, self.encoding)
1548
1549 @property
1550 def encoding(self):
1551 return self._encoding
1552
1553 @property
1554 def errors(self):
1555 return self._errors
1556
1557 @property
1558 def line_buffering(self):
1559 return self._line_buffering
1560
Antoine Pitroufc9ead62010-12-21 21:26:55 +00001561 @property
1562 def buffer(self):
1563 return self._buffer
1564
Antoine Pitrou19690592009-06-12 20:14:08 +00001565 def seekable(self):
Antoine Pitrouc5eec0e2012-09-05 20:11:49 +02001566 if self.closed:
1567 raise ValueError("I/O operation on closed file.")
Antoine Pitrou19690592009-06-12 20:14:08 +00001568 return self._seekable
1569
1570 def readable(self):
1571 return self.buffer.readable()
1572
1573 def writable(self):
1574 return self.buffer.writable()
1575
1576 def flush(self):
1577 self.buffer.flush()
1578 self._telling = self._seekable
1579
1580 def close(self):
Antoine Pitrouf7fd8e42010-05-03 16:25:33 +00001581 if self.buffer is not None and not self.closed:
Benjamin Petersona2d6d712012-12-20 12:24:10 -06001582 try:
1583 self.flush()
1584 finally:
1585 self.buffer.close()
Antoine Pitrou19690592009-06-12 20:14:08 +00001586
1587 @property
1588 def closed(self):
1589 return self.buffer.closed
1590
1591 @property
1592 def name(self):
1593 return self.buffer.name
1594
1595 def fileno(self):
1596 return self.buffer.fileno()
1597
1598 def isatty(self):
1599 return self.buffer.isatty()
1600
1601 def write(self, s):
1602 if self.closed:
1603 raise ValueError("write to closed file")
1604 if not isinstance(s, unicode):
1605 raise TypeError("can't write %s to text stream" %
1606 s.__class__.__name__)
1607 length = len(s)
1608 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1609 if haslf and self._writetranslate and self._writenl != "\n":
1610 s = s.replace("\n", self._writenl)
1611 encoder = self._encoder or self._get_encoder()
1612 # XXX What if we were just reading?
1613 b = encoder.encode(s)
1614 self.buffer.write(b)
1615 if self._line_buffering and (haslf or "\r" in s):
1616 self.flush()
1617 self._snapshot = None
1618 if self._decoder:
1619 self._decoder.reset()
1620 return length
1621
1622 def _get_encoder(self):
1623 make_encoder = codecs.getincrementalencoder(self._encoding)
1624 self._encoder = make_encoder(self._errors)
1625 return self._encoder
1626
1627 def _get_decoder(self):
1628 make_decoder = codecs.getincrementaldecoder(self._encoding)
1629 decoder = make_decoder(self._errors)
1630 if self._readuniversal:
1631 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1632 self._decoder = decoder
1633 return decoder
1634
1635 # The following three methods implement an ADT for _decoded_chars.
1636 # Text returned from the decoder is buffered here until the client
1637 # requests it by calling our read() or readline() method.
1638 def _set_decoded_chars(self, chars):
1639 """Set the _decoded_chars buffer."""
1640 self._decoded_chars = chars
1641 self._decoded_chars_used = 0
1642
1643 def _get_decoded_chars(self, n=None):
1644 """Advance into the _decoded_chars buffer."""
1645 offset = self._decoded_chars_used
1646 if n is None:
1647 chars = self._decoded_chars[offset:]
1648 else:
1649 chars = self._decoded_chars[offset:offset + n]
1650 self._decoded_chars_used += len(chars)
1651 return chars
1652
1653 def _rewind_decoded_chars(self, n):
1654 """Rewind the _decoded_chars buffer."""
1655 if self._decoded_chars_used < n:
1656 raise AssertionError("rewind decoded_chars out of bounds")
1657 self._decoded_chars_used -= n
1658
1659 def _read_chunk(self):
1660 """
1661 Read and decode the next chunk of data from the BufferedReader.
1662 """
1663
1664 # The return value is True unless EOF was reached. The decoded
1665 # string is placed in self._decoded_chars (replacing its previous
1666 # value). The entire input chunk is sent to the decoder, though
1667 # some of it may remain buffered in the decoder, yet to be
1668 # converted.
1669
1670 if self._decoder is None:
1671 raise ValueError("no decoder")
1672
1673 if self._telling:
1674 # To prepare for tell(), we need to snapshot a point in the
1675 # file where the decoder's input buffer is empty.
1676
1677 dec_buffer, dec_flags = self._decoder.getstate()
1678 # Given this, we know there was a valid snapshot point
1679 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1680
1681 # Read a chunk, decode it, and put the result in self._decoded_chars.
1682 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1683 eof = not input_chunk
1684 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1685
1686 if self._telling:
1687 # At the snapshot point, len(dec_buffer) bytes before the read,
1688 # the next input to be decoded is dec_buffer + input_chunk.
1689 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1690
1691 return not eof
1692
1693 def _pack_cookie(self, position, dec_flags=0,
1694 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1695 # The meaning of a tell() cookie is: seek to position, set the
1696 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1697 # into the decoder with need_eof as the EOF flag, then skip
1698 # chars_to_skip characters of the decoded result. For most simple
1699 # decoders, tell() will often just give a byte offset in the file.
1700 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1701 (chars_to_skip<<192) | bool(need_eof)<<256)
1702
1703 def _unpack_cookie(self, bigint):
1704 rest, position = divmod(bigint, 1<<64)
1705 rest, dec_flags = divmod(rest, 1<<64)
1706 rest, bytes_to_feed = divmod(rest, 1<<64)
1707 need_eof, chars_to_skip = divmod(rest, 1<<64)
1708 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1709
1710 def tell(self):
1711 if not self._seekable:
1712 raise IOError("underlying stream is not seekable")
1713 if not self._telling:
1714 raise IOError("telling position disabled by next() call")
1715 self.flush()
1716 position = self.buffer.tell()
1717 decoder = self._decoder
1718 if decoder is None or self._snapshot is None:
1719 if self._decoded_chars:
1720 # This should never happen.
1721 raise AssertionError("pending decoded text")
1722 return position
1723
1724 # Skip backward to the snapshot point (see _read_chunk).
1725 dec_flags, next_input = self._snapshot
1726 position -= len(next_input)
1727
1728 # How many decoded characters have been used up since the snapshot?
1729 chars_to_skip = self._decoded_chars_used
1730 if chars_to_skip == 0:
1731 # We haven't moved from the snapshot point.
1732 return self._pack_cookie(position, dec_flags)
1733
1734 # Starting from the snapshot position, we will walk the decoder
1735 # forward until it gives us enough decoded characters.
1736 saved_state = decoder.getstate()
1737 try:
1738 # Note our initial start point.
1739 decoder.setstate((b'', dec_flags))
1740 start_pos = position
1741 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1742 need_eof = 0
1743
1744 # Feed the decoder one byte at a time. As we go, note the
1745 # nearest "safe start point" before the current location
1746 # (a point where the decoder has nothing buffered, so seek()
1747 # can safely start from there and advance to this location).
1748 for next_byte in next_input:
1749 bytes_fed += 1
1750 chars_decoded += len(decoder.decode(next_byte))
1751 dec_buffer, dec_flags = decoder.getstate()
1752 if not dec_buffer and chars_decoded <= chars_to_skip:
1753 # Decoder buffer is empty, so this is a safe start point.
1754 start_pos += bytes_fed
1755 chars_to_skip -= chars_decoded
1756 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1757 if chars_decoded >= chars_to_skip:
1758 break
1759 else:
1760 # We didn't get enough decoded data; signal EOF to get more.
1761 chars_decoded += len(decoder.decode(b'', final=True))
1762 need_eof = 1
1763 if chars_decoded < chars_to_skip:
1764 raise IOError("can't reconstruct logical file position")
1765
1766 # The returned cookie corresponds to the last safe start point.
1767 return self._pack_cookie(
1768 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1769 finally:
1770 decoder.setstate(saved_state)
1771
1772 def truncate(self, pos=None):
1773 self.flush()
1774 if pos is None:
1775 pos = self.tell()
Antoine Pitrouf3fa0742010-01-31 22:26:04 +00001776 return self.buffer.truncate(pos)
Antoine Pitrou19690592009-06-12 20:14:08 +00001777
1778 def detach(self):
1779 if self.buffer is None:
1780 raise ValueError("buffer is already detached")
1781 self.flush()
Antoine Pitroufc9ead62010-12-21 21:26:55 +00001782 buffer = self._buffer
1783 self._buffer = None
Antoine Pitrou19690592009-06-12 20:14:08 +00001784 return buffer
1785
1786 def seek(self, cookie, whence=0):
1787 if self.closed:
1788 raise ValueError("tell on closed file")
1789 if not self._seekable:
1790 raise IOError("underlying stream is not seekable")
1791 if whence == 1: # seek relative to current position
1792 if cookie != 0:
1793 raise IOError("can't do nonzero cur-relative seeks")
1794 # Seeking to the current position should attempt to
1795 # sync the underlying buffer with the current position.
1796 whence = 0
1797 cookie = self.tell()
1798 if whence == 2: # seek relative to end of file
1799 if cookie != 0:
1800 raise IOError("can't do nonzero end-relative seeks")
1801 self.flush()
1802 position = self.buffer.seek(0, 2)
1803 self._set_decoded_chars('')
1804 self._snapshot = None
1805 if self._decoder:
1806 self._decoder.reset()
1807 return position
1808 if whence != 0:
1809 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1810 (whence,))
1811 if cookie < 0:
1812 raise ValueError("negative seek position %r" % (cookie,))
1813 self.flush()
1814
1815 # The strategy of seek() is to go back to the safe start point
1816 # and replay the effect of read(chars_to_skip) from there.
1817 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1818 self._unpack_cookie(cookie)
1819
1820 # Seek back to the safe start point.
1821 self.buffer.seek(start_pos)
1822 self._set_decoded_chars('')
1823 self._snapshot = None
1824
1825 # Restore the decoder to its state from the safe start point.
1826 if cookie == 0 and self._decoder:
1827 self._decoder.reset()
1828 elif self._decoder or dec_flags or chars_to_skip:
1829 self._decoder = self._decoder or self._get_decoder()
1830 self._decoder.setstate((b'', dec_flags))
1831 self._snapshot = (dec_flags, b'')
1832
1833 if chars_to_skip:
1834 # Just like _read_chunk, feed the decoder and save a snapshot.
1835 input_chunk = self.buffer.read(bytes_to_feed)
1836 self._set_decoded_chars(
1837 self._decoder.decode(input_chunk, need_eof))
1838 self._snapshot = (dec_flags, input_chunk)
1839
1840 # Skip chars_to_skip of the decoded characters.
1841 if len(self._decoded_chars) < chars_to_skip:
1842 raise IOError("can't restore logical file position")
1843 self._decoded_chars_used = chars_to_skip
1844
1845 # Finally, reset the encoder (merely useful for proper BOM handling)
1846 try:
1847 encoder = self._encoder or self._get_encoder()
1848 except LookupError:
1849 # Sometimes the encoder doesn't exist
1850 pass
1851 else:
1852 if cookie != 0:
1853 encoder.setstate(0)
1854 else:
1855 encoder.reset()
1856 return cookie
1857
1858 def read(self, n=None):
1859 self._checkReadable()
1860 if n is None:
1861 n = -1
1862 decoder = self._decoder or self._get_decoder()
Florent Xicluna1f3b4e12010-03-07 12:14:25 +00001863 try:
1864 n.__index__
1865 except AttributeError:
1866 raise TypeError("an integer is required")
Antoine Pitrou19690592009-06-12 20:14:08 +00001867 if n < 0:
1868 # Read everything.
1869 result = (self._get_decoded_chars() +
1870 decoder.decode(self.buffer.read(), final=True))
1871 self._set_decoded_chars('')
1872 self._snapshot = None
1873 return result
1874 else:
1875 # Keep reading chunks until we have n characters to return.
1876 eof = False
1877 result = self._get_decoded_chars(n)
1878 while len(result) < n and not eof:
1879 eof = not self._read_chunk()
1880 result += self._get_decoded_chars(n - len(result))
1881 return result
1882
1883 def next(self):
1884 self._telling = False
1885 line = self.readline()
1886 if not line:
1887 self._snapshot = None
1888 self._telling = self._seekable
1889 raise StopIteration
1890 return line
1891
1892 def readline(self, limit=None):
1893 if self.closed:
1894 raise ValueError("read from closed file")
1895 if limit is None:
1896 limit = -1
1897 elif not isinstance(limit, (int, long)):
1898 raise TypeError("limit must be an integer")
1899
1900 # Grab all the decoded text (we will rewind any extra bits later).
1901 line = self._get_decoded_chars()
1902
1903 start = 0
1904 # Make the decoder if it doesn't already exist.
1905 if not self._decoder:
1906 self._get_decoder()
1907
1908 pos = endpos = None
1909 while True:
1910 if self._readtranslate:
1911 # Newlines are already translated, only search for \n
1912 pos = line.find('\n', start)
1913 if pos >= 0:
1914 endpos = pos + 1
1915 break
1916 else:
1917 start = len(line)
1918
1919 elif self._readuniversal:
1920 # Universal newline search. Find any of \r, \r\n, \n
1921 # The decoder ensures that \r\n are not split in two pieces
1922
1923 # In C we'd look for these in parallel of course.
1924 nlpos = line.find("\n", start)
1925 crpos = line.find("\r", start)
1926 if crpos == -1:
1927 if nlpos == -1:
1928 # Nothing found
1929 start = len(line)
1930 else:
1931 # Found \n
1932 endpos = nlpos + 1
1933 break
1934 elif nlpos == -1:
1935 # Found lone \r
1936 endpos = crpos + 1
1937 break
1938 elif nlpos < crpos:
1939 # Found \n
1940 endpos = nlpos + 1
1941 break
1942 elif nlpos == crpos + 1:
1943 # Found \r\n
1944 endpos = crpos + 2
1945 break
1946 else:
1947 # Found \r
1948 endpos = crpos + 1
1949 break
1950 else:
1951 # non-universal
1952 pos = line.find(self._readnl)
1953 if pos >= 0:
1954 endpos = pos + len(self._readnl)
1955 break
1956
1957 if limit >= 0 and len(line) >= limit:
1958 endpos = limit # reached length limit
1959 break
1960
1961 # No line ending seen yet - get more data'
1962 while self._read_chunk():
1963 if self._decoded_chars:
1964 break
1965 if self._decoded_chars:
1966 line += self._get_decoded_chars()
1967 else:
1968 # end of file
1969 self._set_decoded_chars('')
1970 self._snapshot = None
1971 return line
1972
1973 if limit >= 0 and endpos > limit:
1974 endpos = limit # don't exceed limit
1975
1976 # Rewind _decoded_chars to just after the line ending we found.
1977 self._rewind_decoded_chars(len(line) - endpos)
1978 return line[:endpos]
1979
1980 @property
1981 def newlines(self):
1982 return self._decoder.newlines if self._decoder else None
1983
1984
1985class StringIO(TextIOWrapper):
1986 """Text I/O implementation using an in-memory buffer.
1987
1988 The initial_value argument sets the value of object. The newline
1989 argument is like the one of TextIOWrapper's constructor.
1990 """
1991
1992 def __init__(self, initial_value="", newline="\n"):
1993 super(StringIO, self).__init__(BytesIO(),
1994 encoding="utf-8",
1995 errors="strict",
1996 newline=newline)
1997 # Issue #5645: make universal newlines semantics the same as in the
1998 # C version, even under Windows.
1999 if newline is None:
2000 self._writetranslate = False
2001 if initial_value:
2002 if not isinstance(initial_value, unicode):
2003 initial_value = unicode(initial_value)
2004 self.write(initial_value)
2005 self.seek(0)
2006
2007 def getvalue(self):
2008 self.flush()
Antoine Pitrouc06634a2014-02-02 23:37:29 +01002009 decoder = self._decoder or self._get_decoder()
2010 old_state = decoder.getstate()
2011 decoder.reset()
2012 try:
2013 return decoder.decode(self.buffer.getvalue(), final=True)
2014 finally:
2015 decoder.setstate(old_state)
Antoine Pitrou19690592009-06-12 20:14:08 +00002016
2017 def __repr__(self):
2018 # TextIOWrapper tells the encoding in its repr. In StringIO,
2019 # that's a implementation detail.
2020 return object.__repr__(self)
2021
2022 @property
2023 def errors(self):
2024 return None
2025
2026 @property
2027 def encoding(self):
2028 return None
2029
2030 def detach(self):
2031 # This doesn't make sense on StringIO.
2032 self._unsupported("detach")