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