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