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