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