blob: 2d376d83002db72df196b0f179f8b4c6786c1ddf [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
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01009import errno
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000010# Import _thread instead of threading to reduce startup cost
11try:
12 from _thread import allocate_lock as Lock
13except ImportError:
14 from _dummy_thread import allocate_lock as Lock
15
16import io
Benjamin Petersonc3be11a2010-04-27 21:24:03 +000017from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
Antoine Pitroud843c2d2011-02-25 21:34:39 +000018from errno import EINTR
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000019
20# open() uses st_blksize whenever we can
21DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
22
23# NOTE: Base classes defined here are registered with the "official" ABCs
24# defined in io.py. We don't use real inheritance though, because we don't
25# want to inherit the C implementations.
26
27
28class BlockingIOError(IOError):
29
30 """Exception raised when I/O would block on a non-blocking I/O stream."""
31
32 def __init__(self, errno, strerror, characters_written=0):
33 super().__init__(errno, strerror)
34 if not isinstance(characters_written, int):
35 raise TypeError("characters_written must be a integer")
36 self.characters_written = characters_written
37
38
Georg Brandl4d73b572011-01-13 07:13:06 +000039def open(file, mode="r", buffering=-1, encoding=None, errors=None,
40 newline=None, closefd=True):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000041
42 r"""Open file and return a stream. Raise IOError upon failure.
43
44 file is either a text or byte string giving the name (and the path
45 if the file isn't in the current working directory) of the file to
46 be opened or an integer file descriptor of the file to be
47 wrapped. (If a file descriptor is given, it is closed when the
48 returned I/O object is closed, unless closefd is set to False.)
49
50 mode is an optional string that specifies the mode in which the file
51 is opened. It defaults to 'r' which means open for reading in text
52 mode. Other common values are 'w' for writing (truncating the file if
53 it already exists), and 'a' for appending (which on some Unix systems,
54 means that all writes append to the end of the file regardless of the
55 current seek position). In text mode, if encoding is not specified the
56 encoding used is platform dependent. (For reading and writing raw
57 bytes use binary mode and leave encoding unspecified.) The available
58 modes are:
59
60 ========= ===============================================================
61 Character Meaning
62 --------- ---------------------------------------------------------------
63 'r' open for reading (default)
64 'w' open for writing, truncating the file first
65 'a' open for writing, appending to the end of the file if it exists
66 'b' binary mode
67 't' text mode (default)
68 '+' open a disk file for updating (reading and writing)
69 'U' universal newline mode (for backwards compatibility; unneeded
70 for new code)
71 ========= ===============================================================
72
73 The default mode is 'rt' (open for reading text). For binary random
74 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
75 'r+b' opens the file without truncation.
76
77 Python distinguishes between files opened in binary and text modes,
78 even when the underlying operating system doesn't. Files opened in
79 binary mode (appending 'b' to the mode argument) return contents as
80 bytes objects without any decoding. In text mode (the default, or when
81 't' is appended to the mode argument), the contents of the file are
82 returned as strings, the bytes having been first decoded using a
83 platform-dependent encoding or using the specified encoding if given.
84
Antoine Pitroud5587bc2009-12-19 21:08:31 +000085 buffering is an optional integer used to set the buffering policy.
86 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
87 line buffering (only usable in text mode), and an integer > 1 to indicate
88 the size of a fixed-size chunk buffer. When no buffering argument is
89 given, the default buffering policy works as follows:
90
91 * Binary files are buffered in fixed-size chunks; the size of the buffer
92 is chosen using a heuristic trying to determine the underlying device's
93 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
94 On many systems, the buffer will typically be 4096 or 8192 bytes long.
95
96 * "Interactive" text files (files for which isatty() returns True)
97 use line buffering. Other text files use the policy described above
98 for binary files.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000099
Raymond Hettingercbb80892011-01-13 18:15:51 +0000100 encoding is the str name of the encoding used to decode or encode the
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000101 file. This should only be used in text mode. The default encoding is
102 platform dependent, but any encoding supported by Python can be
103 passed. See the codecs module for the list of supported encodings.
104
105 errors is an optional string that specifies how encoding errors are to
106 be handled---this argument should not be used in binary mode. Pass
107 'strict' to raise a ValueError exception if there is an encoding error
108 (the default of None has the same effect), or pass 'ignore' to ignore
109 errors. (Note that ignoring encoding errors can lead to data loss.)
110 See the documentation for codecs.register for a list of the permitted
111 encoding error strings.
112
Raymond Hettingercbb80892011-01-13 18:15:51 +0000113 newline is a string controlling how universal newlines works (it only
114 applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
115 as follows:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116
117 * On input, if newline is None, universal newlines mode is
118 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
119 these are translated into '\n' before being returned to the
120 caller. If it is '', universal newline mode is enabled, but line
121 endings are returned to the caller untranslated. If it has any of
122 the other legal values, input lines are only terminated by the given
123 string, and the line ending is returned to the caller untranslated.
124
125 * On output, if newline is None, any '\n' characters written are
126 translated to the system default line separator, os.linesep. If
127 newline is '', no translation takes place. If newline is any of the
128 other legal values, any '\n' characters written are translated to
129 the given string.
130
Raymond Hettingercbb80892011-01-13 18:15:51 +0000131 closedfd is a bool. If closefd is False, the underlying file descriptor will
132 be kept open when the file is closed. This does not work when a file name is
133 given and must be True in that case.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000134
135 open() returns a file object whose type depends on the mode, and
136 through which the standard file operations such as reading and writing
137 are performed. When open() is used to open a file in a text mode ('w',
138 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
139 a file in a binary mode, the returned class varies: in read binary
140 mode, it returns a BufferedReader; in write binary and append binary
141 modes, it returns a BufferedWriter, and in read/write mode, it returns
142 a BufferedRandom.
143
144 It is also possible to use a string or bytearray as a file for both
145 reading and writing. For strings StringIO can be used like a file
146 opened in a text mode, and for bytes a BytesIO can be used like a file
147 opened in a binary mode.
148 """
149 if not isinstance(file, (str, bytes, int)):
150 raise TypeError("invalid file: %r" % file)
151 if not isinstance(mode, str):
152 raise TypeError("invalid mode: %r" % mode)
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000153 if not isinstance(buffering, int):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000154 raise TypeError("invalid buffering: %r" % buffering)
155 if encoding is not None and not isinstance(encoding, str):
156 raise TypeError("invalid encoding: %r" % encoding)
157 if errors is not None and not isinstance(errors, str):
158 raise TypeError("invalid errors: %r" % errors)
159 modes = set(mode)
160 if modes - set("arwb+tU") or len(mode) > len(modes):
161 raise ValueError("invalid mode: %r" % mode)
162 reading = "r" in modes
163 writing = "w" in modes
164 appending = "a" in modes
165 updating = "+" in modes
166 text = "t" in modes
167 binary = "b" in modes
168 if "U" in modes:
169 if writing or appending:
170 raise ValueError("can't use U and writing mode at once")
171 reading = True
172 if text and binary:
173 raise ValueError("can't have text and binary mode at once")
174 if reading + writing + appending > 1:
175 raise ValueError("can't have read/write/append mode at once")
176 if not (reading or writing or appending):
177 raise ValueError("must have exactly one of read/write/append mode")
178 if binary and encoding is not None:
179 raise ValueError("binary mode doesn't take an encoding argument")
180 if binary and errors is not None:
181 raise ValueError("binary mode doesn't take an errors argument")
182 if binary and newline is not None:
183 raise ValueError("binary mode doesn't take a newline argument")
184 raw = FileIO(file,
185 (reading and "r" or "") +
186 (writing and "w" or "") +
187 (appending and "a" or "") +
188 (updating and "+" or ""),
189 closefd)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000190 line_buffering = False
191 if buffering == 1 or buffering < 0 and raw.isatty():
192 buffering = -1
193 line_buffering = True
194 if buffering < 0:
195 buffering = DEFAULT_BUFFER_SIZE
196 try:
197 bs = os.fstat(raw.fileno()).st_blksize
198 except (os.error, AttributeError):
199 pass
200 else:
201 if bs > 1:
202 buffering = bs
203 if buffering < 0:
204 raise ValueError("invalid buffering size")
205 if buffering == 0:
206 if binary:
207 return raw
208 raise ValueError("can't have unbuffered text I/O")
209 if updating:
210 buffer = BufferedRandom(raw, buffering)
211 elif writing or appending:
212 buffer = BufferedWriter(raw, buffering)
213 elif reading:
214 buffer = BufferedReader(raw, buffering)
215 else:
216 raise ValueError("unknown mode: %r" % mode)
217 if binary:
218 return buffer
219 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
220 text.mode = mode
221 return text
222
223
224class DocDescriptor:
225 """Helper for builtins.open.__doc__
226 """
227 def __get__(self, obj, typ):
228 return (
Benjamin Petersonc3be11a2010-04-27 21:24:03 +0000229 "open(file, mode='r', buffering=-1, encoding=None, "
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000230 "errors=None, newline=None, closefd=True)\n\n" +
231 open.__doc__)
232
233class OpenWrapper:
234 """Wrapper for builtins.open
235
236 Trick so that open won't become a bound method when stored
237 as a class variable (as dbm.dumb does).
238
239 See initstdio() in Python/pythonrun.c.
240 """
241 __doc__ = DocDescriptor()
242
243 def __new__(cls, *args, **kwargs):
244 return open(*args, **kwargs)
245
246
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000247# In normal operation, both `UnsupportedOperation`s should be bound to the
248# same object.
249try:
250 UnsupportedOperation = io.UnsupportedOperation
251except AttributeError:
252 class UnsupportedOperation(ValueError, IOError):
253 pass
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000254
255
256class IOBase(metaclass=abc.ABCMeta):
257
258 """The abstract base class for all I/O classes, acting on streams of
259 bytes. There is no public constructor.
260
261 This class provides dummy implementations for many methods that
262 derived classes can override selectively; the default implementations
263 represent a file that cannot be read, written or seeked.
264
265 Even though IOBase does not declare read, readinto, or write because
266 their signatures will vary, implementations and clients should
267 consider those methods part of the interface. Also, implementations
Amaury Forgeot d'Arc616453c2010-09-06 22:31:52 +0000268 may raise UnsupportedOperation when operations they do not support are
269 called.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000270
271 The basic type used for binary data read from or written to a file is
272 bytes. bytearrays are accepted too, and in some cases (such as
273 readinto) needed. Text I/O classes work with str data.
274
275 Note that calling any method (even inquiries) on a closed stream is
276 undefined. Implementations may raise IOError in this case.
277
278 IOBase (and its subclasses) support the iterator protocol, meaning
279 that an IOBase object can be iterated over yielding the lines in a
280 stream.
281
282 IOBase also supports the :keyword:`with` statement. In this example,
283 fp is closed after the suite of the with statement is complete:
284
285 with open('spam.txt', 'r') as fp:
286 fp.write('Spam and eggs!')
287 """
288
289 ### Internal ###
290
Raymond Hettinger3c940242011-01-12 23:39:31 +0000291 def _unsupported(self, name):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000292 """Internal: raise an IOError exception for unsupported operations."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000293 raise UnsupportedOperation("%s.%s() not supported" %
294 (self.__class__.__name__, name))
295
296 ### Positioning ###
297
Georg Brandl4d73b572011-01-13 07:13:06 +0000298 def seek(self, pos, whence=0):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000299 """Change stream position.
300
301 Change the stream position to byte offset offset. offset is
302 interpreted relative to the position indicated by whence. Values
Raymond Hettingercbb80892011-01-13 18:15:51 +0000303 for whence are ints:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000304
305 * 0 -- start of stream (the default); offset should be zero or positive
306 * 1 -- current stream position; offset may be negative
307 * 2 -- end of stream; offset is usually negative
308
Raymond Hettingercbb80892011-01-13 18:15:51 +0000309 Return an int indicating the new absolute position.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000310 """
311 self._unsupported("seek")
312
Raymond Hettinger3c940242011-01-12 23:39:31 +0000313 def tell(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000314 """Return an int indicating the current stream position."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000315 return self.seek(0, 1)
316
Georg Brandl4d73b572011-01-13 07:13:06 +0000317 def truncate(self, pos=None):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000318 """Truncate file to size bytes.
319
320 Size defaults to the current IO position as reported by tell(). Return
321 the new size.
322 """
323 self._unsupported("truncate")
324
325 ### Flush and close ###
326
Raymond Hettinger3c940242011-01-12 23:39:31 +0000327 def flush(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000328 """Flush write buffers, if applicable.
329
330 This is not implemented for read-only and non-blocking streams.
331 """
Antoine Pitrou6be88762010-05-03 16:48:20 +0000332 self._checkClosed()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000333 # XXX Should this return the number of bytes written???
334
335 __closed = False
336
Raymond Hettinger3c940242011-01-12 23:39:31 +0000337 def close(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000338 """Flush and close the IO object.
339
340 This method has no effect if the file is already closed.
341 """
342 if not self.__closed:
Antoine Pitrou6be88762010-05-03 16:48:20 +0000343 self.flush()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000344 self.__closed = True
345
Raymond Hettinger3c940242011-01-12 23:39:31 +0000346 def __del__(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000347 """Destructor. Calls close()."""
348 # The try/except block is in case this is called at program
349 # exit time, when it's possible that globals have already been
350 # deleted, and then the close() call might fail. Since
351 # there's nothing we can do about such failures and they annoy
352 # the end users, we suppress the traceback.
353 try:
354 self.close()
355 except:
356 pass
357
358 ### Inquiries ###
359
Raymond Hettinger3c940242011-01-12 23:39:31 +0000360 def seekable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000361 """Return a bool indicating whether object supports random access.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000362
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000363 If False, seek(), tell() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000364 This method may need to do a test seek().
365 """
366 return False
367
368 def _checkSeekable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000369 """Internal: raise UnsupportedOperation if file is not seekable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000370 """
371 if not self.seekable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000372 raise UnsupportedOperation("File or stream is not seekable."
373 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000374
Raymond Hettinger3c940242011-01-12 23:39:31 +0000375 def readable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000376 """Return a bool indicating whether object was opened for reading.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000377
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000378 If False, read() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000379 """
380 return False
381
382 def _checkReadable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000383 """Internal: raise UnsupportedOperation if file is not readable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000384 """
385 if not self.readable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000386 raise UnsupportedOperation("File or stream is not readable."
387 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388
Raymond Hettinger3c940242011-01-12 23:39:31 +0000389 def writable(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000390 """Return a bool indicating whether object was opened for writing.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000391
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000392 If False, write() and truncate() will raise UnsupportedOperation.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393 """
394 return False
395
396 def _checkWritable(self, msg=None):
Amaury Forgeot d'Arcada99482010-09-06 22:23:13 +0000397 """Internal: raise UnsupportedOperation if file is not writable
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000398 """
399 if not self.writable():
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000400 raise UnsupportedOperation("File or stream is not writable."
401 if msg is None else msg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000402
403 @property
404 def closed(self):
405 """closed: bool. True iff the file has been closed.
406
407 For backwards compatibility, this is a property, not a predicate.
408 """
409 return self.__closed
410
411 def _checkClosed(self, msg=None):
412 """Internal: raise an ValueError if file is closed
413 """
414 if self.closed:
415 raise ValueError("I/O operation on closed file."
416 if msg is None else msg)
417
418 ### Context manager ###
419
Raymond Hettinger3c940242011-01-12 23:39:31 +0000420 def __enter__(self): # That's a forward reference
Raymond Hettingercbb80892011-01-13 18:15:51 +0000421 """Context management protocol. Returns self (an instance of IOBase)."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422 self._checkClosed()
423 return self
424
Raymond Hettinger3c940242011-01-12 23:39:31 +0000425 def __exit__(self, *args):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000426 """Context management protocol. Calls close()"""
427 self.close()
428
429 ### Lower-level APIs ###
430
431 # XXX Should these be present even if unimplemented?
432
Raymond Hettinger3c940242011-01-12 23:39:31 +0000433 def fileno(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000434 """Returns underlying file descriptor (an int) if one exists.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000435
436 An IOError is raised if the IO object does not use a file descriptor.
437 """
438 self._unsupported("fileno")
439
Raymond Hettinger3c940242011-01-12 23:39:31 +0000440 def isatty(self):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000441 """Return a bool indicating whether this is an 'interactive' stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000442
443 Return False if it can't be determined.
444 """
445 self._checkClosed()
446 return False
447
448 ### Readline[s] and writelines ###
449
Georg Brandl4d73b572011-01-13 07:13:06 +0000450 def readline(self, limit=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000451 r"""Read and return a line of bytes from the stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000452
453 If limit is specified, at most limit bytes will be read.
Raymond Hettingercbb80892011-01-13 18:15:51 +0000454 Limit should be an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000455
456 The line terminator is always b'\n' for binary files; for text
457 files, the newlines argument to open can be used to select the line
458 terminator(s) recognized.
459 """
460 # For backwards compatibility, a (slowish) readline().
461 if hasattr(self, "peek"):
462 def nreadahead():
463 readahead = self.peek(1)
464 if not readahead:
465 return 1
466 n = (readahead.find(b"\n") + 1) or len(readahead)
467 if limit >= 0:
468 n = min(n, limit)
469 return n
470 else:
471 def nreadahead():
472 return 1
473 if limit is None:
474 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +0000475 elif not isinstance(limit, int):
476 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000477 res = bytearray()
478 while limit < 0 or len(res) < limit:
479 b = self.read(nreadahead())
480 if not b:
481 break
482 res += b
483 if res.endswith(b"\n"):
484 break
485 return bytes(res)
486
487 def __iter__(self):
488 self._checkClosed()
489 return self
490
491 def __next__(self):
492 line = self.readline()
493 if not line:
494 raise StopIteration
495 return line
496
497 def readlines(self, hint=None):
498 """Return a list of lines from the stream.
499
500 hint can be specified to control the number of lines read: no more
501 lines will be read if the total size (in bytes/characters) of all
502 lines so far exceeds hint.
503 """
504 if hint is 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
Georg Brandl4d73b572011-01-13 07:13:06 +0000537 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000538 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000539
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 Pitrou328ec742010-09-14 18:37:24 +0000549 if n is None:
550 return None
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +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
Victor Stinnera80987f2011-05-25 22:47:16 +0200562 if res:
563 return bytes(res)
564 else:
565 # b'' or None
566 return data
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567
Raymond Hettinger3c940242011-01-12 23:39:31 +0000568 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000569 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570
Raymond Hettingercbb80892011-01-13 18:15:51 +0000571 Returns an int representing the number of bytes read (0 for EOF), or
572 None if the object is set not to block and has no data to read.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573 """
574 self._unsupported("readinto")
575
Raymond Hettinger3c940242011-01-12 23:39:31 +0000576 def write(self, b):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000577 """Write the given buffer to the IO stream.
578
579 Returns the number of bytes written, which may be less than len(b).
580 """
581 self._unsupported("write")
582
583io.RawIOBase.register(RawIOBase)
584from _io import FileIO
585RawIOBase.register(FileIO)
586
587
588class BufferedIOBase(IOBase):
589
590 """Base class for buffered IO objects.
591
592 The main difference with RawIOBase is that the read() method
593 supports omitting the size argument, and does not have a default
594 implementation that defers to readinto().
595
596 In addition, read(), readinto() and write() may raise
597 BlockingIOError if the underlying raw stream is in non-blocking
598 mode and not ready; unlike their raw counterparts, they will never
599 return None.
600
601 A typical implementation should not inherit from a RawIOBase
602 implementation, but wrap one.
603 """
604
Georg Brandl4d73b572011-01-13 07:13:06 +0000605 def read(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000606 """Read and return up to n bytes, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000607
608 If the argument is omitted, None, or negative, reads and
609 returns all data until EOF.
610
611 If the argument is positive, and the underlying raw stream is
612 not 'interactive', multiple raw reads may be issued to satisfy
613 the byte count (unless EOF is reached first). But for
614 interactive raw streams (XXX and for pipes?), at most one raw
615 read will be issued, and a short result does not imply that
616 EOF is imminent.
617
618 Returns an empty bytes array on EOF.
619
620 Raises BlockingIOError if the underlying raw stream has no
621 data at the moment.
622 """
623 self._unsupported("read")
624
Georg Brandl4d73b572011-01-13 07:13:06 +0000625 def read1(self, n=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000626 """Read up to n bytes with at most one read() system call,
627 where n is an int.
628 """
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000629 self._unsupported("read1")
630
Raymond Hettinger3c940242011-01-12 23:39:31 +0000631 def readinto(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000632 """Read up to len(b) bytes into bytearray b.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000633
634 Like read(), this may issue multiple reads to the underlying raw
635 stream, unless the latter is 'interactive'.
636
Raymond Hettingercbb80892011-01-13 18:15:51 +0000637 Returns an int representing the number of bytes read (0 for EOF).
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000638
639 Raises BlockingIOError if the underlying raw stream has no
640 data at the moment.
641 """
642 # XXX This ought to work with anything that supports the buffer API
643 data = self.read(len(b))
644 n = len(data)
645 try:
646 b[:n] = data
647 except TypeError as err:
648 import array
649 if not isinstance(b, array.array):
650 raise err
651 b[:n] = array.array('b', data)
652 return n
653
Raymond Hettinger3c940242011-01-12 23:39:31 +0000654 def write(self, b):
Raymond Hettingercbb80892011-01-13 18:15:51 +0000655 """Write the given bytes buffer to the IO stream.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000656
657 Return the number of bytes written, which is never less than
658 len(b).
659
660 Raises BlockingIOError if the buffer is full and the
661 underlying raw stream cannot accept more data at the moment.
662 """
663 self._unsupported("write")
664
Raymond Hettinger3c940242011-01-12 23:39:31 +0000665 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000666 """
667 Separate the underlying raw stream from the buffer and return it.
668
669 After the raw stream has been detached, the buffer is in an unusable
670 state.
671 """
672 self._unsupported("detach")
673
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000674io.BufferedIOBase.register(BufferedIOBase)
675
676
677class _BufferedIOMixin(BufferedIOBase):
678
679 """A mixin implementation of BufferedIOBase with an underlying raw stream.
680
681 This passes most requests on to the underlying raw stream. It
682 does *not* provide implementations of read(), readinto() or
683 write().
684 """
685
686 def __init__(self, raw):
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000687 self._raw = raw
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000688
689 ### Positioning ###
690
691 def seek(self, pos, whence=0):
692 new_position = self.raw.seek(pos, whence)
693 if new_position < 0:
694 raise IOError("seek() returned an invalid position")
695 return new_position
696
697 def tell(self):
698 pos = self.raw.tell()
699 if pos < 0:
700 raise IOError("tell() returned an invalid position")
701 return pos
702
703 def truncate(self, pos=None):
704 # Flush the stream. We're mixing buffered I/O with lower-level I/O,
705 # and a flush may be necessary to synch both views of the current
706 # file state.
707 self.flush()
708
709 if pos is None:
710 pos = self.tell()
711 # XXX: Should seek() be used, instead of passing the position
712 # XXX directly to truncate?
713 return self.raw.truncate(pos)
714
715 ### Flush and close ###
716
717 def flush(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000718 if self.closed:
719 raise ValueError("flush of closed file")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000720 self.raw.flush()
721
722 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +0000723 if self.raw is not None and not self.closed:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +0100724 try:
725 # may raise BlockingIOError or BrokenPipeError etc
726 self.flush()
727 finally:
728 self.raw.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000729
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000730 def detach(self):
731 if self.raw is None:
732 raise ValueError("raw stream already detached")
733 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000734 raw = self._raw
735 self._raw = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000736 return raw
737
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000738 ### Inquiries ###
739
740 def seekable(self):
741 return self.raw.seekable()
742
743 def readable(self):
744 return self.raw.readable()
745
746 def writable(self):
747 return self.raw.writable()
748
749 @property
Antoine Pitrou7f8f4182010-12-21 21:20:59 +0000750 def raw(self):
751 return self._raw
752
753 @property
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000754 def closed(self):
755 return self.raw.closed
756
757 @property
758 def name(self):
759 return self.raw.name
760
761 @property
762 def mode(self):
763 return self.raw.mode
764
Antoine Pitrou243757e2010-11-05 21:15:39 +0000765 def __getstate__(self):
766 raise TypeError("can not serialize a '{0}' object"
767 .format(self.__class__.__name__))
768
Antoine Pitrou716c4442009-05-23 19:04:03 +0000769 def __repr__(self):
770 clsname = self.__class__.__name__
771 try:
772 name = self.name
773 except AttributeError:
774 return "<_pyio.{0}>".format(clsname)
775 else:
776 return "<_pyio.{0} name={1!r}>".format(clsname, name)
777
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000778 ### Lower-level APIs ###
779
780 def fileno(self):
781 return self.raw.fileno()
782
783 def isatty(self):
784 return self.raw.isatty()
785
786
787class BytesIO(BufferedIOBase):
788
789 """Buffered I/O implementation using an in-memory bytes buffer."""
790
791 def __init__(self, initial_bytes=None):
792 buf = bytearray()
793 if initial_bytes is not None:
794 buf += initial_bytes
795 self._buffer = buf
796 self._pos = 0
797
Alexandre Vassalotticf76e1a2009-07-22 03:24:36 +0000798 def __getstate__(self):
799 if self.closed:
800 raise ValueError("__getstate__ on closed file")
801 return self.__dict__.copy()
802
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000803 def getvalue(self):
804 """Return the bytes value (contents) of the buffer
805 """
806 if self.closed:
807 raise ValueError("getvalue on closed file")
808 return bytes(self._buffer)
809
Antoine Pitrou972ee132010-09-06 18:48:21 +0000810 def getbuffer(self):
811 """Return a readable and writable view of the buffer.
812 """
813 return memoryview(self._buffer)
814
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000815 def read(self, n=None):
816 if self.closed:
817 raise ValueError("read from closed file")
818 if n is None:
819 n = -1
820 if n < 0:
821 n = len(self._buffer)
822 if len(self._buffer) <= self._pos:
823 return b""
824 newpos = min(len(self._buffer), self._pos + n)
825 b = self._buffer[self._pos : newpos]
826 self._pos = newpos
827 return bytes(b)
828
829 def read1(self, n):
830 """This is the same as read.
831 """
832 return self.read(n)
833
834 def write(self, b):
835 if self.closed:
836 raise ValueError("write to closed file")
837 if isinstance(b, str):
838 raise TypeError("can't write str to binary stream")
839 n = len(b)
840 if n == 0:
841 return 0
842 pos = self._pos
843 if pos > len(self._buffer):
844 # Inserts null bytes between the current end of the file
845 # and the new write position.
846 padding = b'\x00' * (pos - len(self._buffer))
847 self._buffer += padding
848 self._buffer[pos:pos + n] = b
849 self._pos += n
850 return n
851
852 def seek(self, pos, whence=0):
853 if self.closed:
854 raise ValueError("seek on closed file")
855 try:
Florent Xiclunab14930c2010-03-13 15:26:44 +0000856 pos.__index__
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000857 except AttributeError as err:
858 raise TypeError("an integer is required") from err
859 if whence == 0:
860 if pos < 0:
861 raise ValueError("negative seek position %r" % (pos,))
862 self._pos = pos
863 elif whence == 1:
864 self._pos = max(0, self._pos + pos)
865 elif whence == 2:
866 self._pos = max(0, len(self._buffer) + pos)
867 else:
868 raise ValueError("invalid whence value")
869 return self._pos
870
871 def tell(self):
872 if self.closed:
873 raise ValueError("tell on closed file")
874 return self._pos
875
876 def truncate(self, pos=None):
877 if self.closed:
878 raise ValueError("truncate on closed file")
879 if pos is None:
880 pos = self._pos
Florent Xiclunab14930c2010-03-13 15:26:44 +0000881 else:
882 try:
883 pos.__index__
884 except AttributeError as err:
885 raise TypeError("an integer is required") from err
886 if pos < 0:
887 raise ValueError("negative truncate position %r" % (pos,))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000888 del self._buffer[pos:]
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000889 return pos
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000890
891 def readable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200892 if self.closed:
893 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000894 return True
895
896 def writable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200897 if self.closed:
898 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000899 return True
900
901 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +0200902 if self.closed:
903 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000904 return True
905
906
907class BufferedReader(_BufferedIOMixin):
908
909 """BufferedReader(raw[, buffer_size])
910
911 A buffer for a readable, sequential BaseRawIO object.
912
913 The constructor creates a BufferedReader for the given readable raw
914 stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
915 is used.
916 """
917
918 def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
919 """Create a new buffered reader using the given readable raw IO object.
920 """
Antoine Pitroucf4c7492009-04-19 00:09:36 +0000921 if not raw.readable():
922 raise IOError('"raw" argument must be readable.')
923
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000924 _BufferedIOMixin.__init__(self, raw)
925 if buffer_size <= 0:
926 raise ValueError("invalid buffer size")
927 self.buffer_size = buffer_size
928 self._reset_read_buf()
929 self._read_lock = Lock()
930
931 def _reset_read_buf(self):
932 self._read_buf = b""
933 self._read_pos = 0
934
935 def read(self, n=None):
936 """Read n bytes.
937
938 Returns exactly n bytes of data unless the underlying raw IO
939 stream reaches EOF or if the call would block in non-blocking
940 mode. If n is negative, read until EOF or until read() would
941 block.
942 """
943 if n is not None and n < -1:
944 raise ValueError("invalid number of bytes to read")
945 with self._read_lock:
946 return self._read_unlocked(n)
947
948 def _read_unlocked(self, n=None):
949 nodata_val = b""
950 empty_values = (b"", None)
951 buf = self._read_buf
952 pos = self._read_pos
953
954 # Special case for when the number of bytes to read is unspecified.
955 if n is None or n == -1:
956 self._reset_read_buf()
957 chunks = [buf[pos:]] # Strip the consumed bytes.
958 current_size = 0
959 while True:
960 # Read until EOF or until read() would block.
Antoine Pitroud843c2d2011-02-25 21:34:39 +0000961 try:
962 chunk = self.raw.read()
963 except IOError as e:
964 if e.errno != EINTR:
965 raise
966 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000967 if chunk in empty_values:
968 nodata_val = chunk
969 break
970 current_size += len(chunk)
971 chunks.append(chunk)
972 return b"".join(chunks) or nodata_val
973
974 # The number of bytes to read is specified, return at most n bytes.
975 avail = len(buf) - pos # Length of the available buffered data.
976 if n <= avail:
977 # Fast path: the data to read is fully buffered.
978 self._read_pos += n
979 return buf[pos:pos+n]
980 # Slow path: read from the stream until enough bytes are read,
981 # or until an EOF occurs or until read() would block.
982 chunks = [buf[pos:]]
983 wanted = max(self.buffer_size, n)
984 while avail < n:
Antoine Pitroud843c2d2011-02-25 21:34:39 +0000985 try:
986 chunk = self.raw.read(wanted)
987 except IOError as e:
988 if e.errno != EINTR:
989 raise
990 continue
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000991 if chunk in empty_values:
992 nodata_val = chunk
993 break
994 avail += len(chunk)
995 chunks.append(chunk)
996 # n is more then avail only when an EOF occurred or when
997 # read() would have blocked.
998 n = min(n, avail)
999 out = b"".join(chunks)
1000 self._read_buf = out[n:] # Save the extra data in the buffer.
1001 self._read_pos = 0
1002 return out[:n] if out else nodata_val
1003
1004 def peek(self, n=0):
1005 """Returns buffered bytes without advancing the position.
1006
1007 The argument indicates a desired minimal number of bytes; we
1008 do at most one raw read to satisfy it. We never return more
1009 than self.buffer_size.
1010 """
1011 with self._read_lock:
1012 return self._peek_unlocked(n)
1013
1014 def _peek_unlocked(self, n=0):
1015 want = min(n, self.buffer_size)
1016 have = len(self._read_buf) - self._read_pos
1017 if have < want or have <= 0:
1018 to_read = self.buffer_size - have
Antoine Pitroud843c2d2011-02-25 21:34:39 +00001019 while True:
1020 try:
1021 current = self.raw.read(to_read)
1022 except IOError as e:
1023 if e.errno != EINTR:
1024 raise
1025 continue
1026 break
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001027 if current:
1028 self._read_buf = self._read_buf[self._read_pos:] + current
1029 self._read_pos = 0
1030 return self._read_buf[self._read_pos:]
1031
1032 def read1(self, n):
1033 """Reads up to n bytes, with at most one read() system call."""
1034 # Returns up to n bytes. If at least one byte is buffered, we
1035 # only return buffered bytes. Otherwise, we do one raw read.
1036 if n < 0:
1037 raise ValueError("number of bytes to read must be positive")
1038 if n == 0:
1039 return b""
1040 with self._read_lock:
1041 self._peek_unlocked(1)
1042 return self._read_unlocked(
1043 min(n, len(self._read_buf) - self._read_pos))
1044
1045 def tell(self):
1046 return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
1047
1048 def seek(self, pos, whence=0):
1049 if not (0 <= whence <= 2):
1050 raise ValueError("invalid whence value")
1051 with self._read_lock:
1052 if whence == 1:
1053 pos -= len(self._read_buf) - self._read_pos
1054 pos = _BufferedIOMixin.seek(self, pos, whence)
1055 self._reset_read_buf()
1056 return pos
1057
1058class BufferedWriter(_BufferedIOMixin):
1059
1060 """A buffer for a writeable sequential RawIO object.
1061
1062 The constructor creates a BufferedWriter for the given writeable raw
1063 stream. If the buffer_size is not given, it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001064 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001065 """
1066
Benjamin Peterson59406a92009-03-26 17:10:29 +00001067 _warning_stack_offset = 2
1068
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001069 def __init__(self, raw,
1070 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001071 if not raw.writable():
1072 raise IOError('"raw" argument must be writable.')
1073
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001074 _BufferedIOMixin.__init__(self, raw)
1075 if buffer_size <= 0:
1076 raise ValueError("invalid buffer size")
Benjamin Peterson59406a92009-03-26 17:10:29 +00001077 if max_buffer_size is not None:
1078 warnings.warn("max_buffer_size is deprecated", DeprecationWarning,
1079 self._warning_stack_offset)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001080 self.buffer_size = buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001081 self._write_buf = bytearray()
1082 self._write_lock = Lock()
1083
1084 def write(self, b):
1085 if self.closed:
1086 raise ValueError("write to closed file")
1087 if isinstance(b, str):
1088 raise TypeError("can't write str to binary stream")
1089 with self._write_lock:
1090 # XXX we can implement some more tricks to try and avoid
1091 # partial writes
1092 if len(self._write_buf) > self.buffer_size:
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001093 # We're full, so let's pre-flush the buffer. (This may
1094 # raise BlockingIOError with characters_written == 0.)
1095 self._flush_unlocked()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001096 before = len(self._write_buf)
1097 self._write_buf.extend(b)
1098 written = len(self._write_buf) - before
1099 if len(self._write_buf) > self.buffer_size:
1100 try:
1101 self._flush_unlocked()
1102 except BlockingIOError as e:
Benjamin Peterson394ee002009-03-05 22:33:59 +00001103 if len(self._write_buf) > self.buffer_size:
1104 # We've hit the buffer_size. We have to accept a partial
1105 # write and cut back our buffer.
1106 overage = len(self._write_buf) - self.buffer_size
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001107 written -= overage
Benjamin Peterson394ee002009-03-05 22:33:59 +00001108 self._write_buf = self._write_buf[:self.buffer_size]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001109 raise BlockingIOError(e.errno, e.strerror, written)
1110 return written
1111
1112 def truncate(self, pos=None):
1113 with self._write_lock:
1114 self._flush_unlocked()
1115 if pos is None:
1116 pos = self.raw.tell()
1117 return self.raw.truncate(pos)
1118
1119 def flush(self):
1120 with self._write_lock:
1121 self._flush_unlocked()
1122
1123 def _flush_unlocked(self):
1124 if self.closed:
1125 raise ValueError("flush of closed file")
Antoine Pitrou58fcf9f2011-11-21 20:16:44 +01001126 while self._write_buf:
1127 try:
1128 n = self.raw.write(self._write_buf)
1129 except BlockingIOError:
1130 raise RuntimeError("self.raw should implement RawIOBase: it "
1131 "should not raise BlockingIOError")
1132 except IOError as e:
1133 if e.errno != EINTR:
1134 raise
1135 continue
1136 if n is None:
1137 raise BlockingIOError(
1138 errno.EAGAIN,
1139 "write could not complete without blocking", 0)
1140 if n > len(self._write_buf) or n < 0:
1141 raise IOError("write() returned incorrect number of bytes")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001142 del self._write_buf[:n]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001143
1144 def tell(self):
1145 return _BufferedIOMixin.tell(self) + len(self._write_buf)
1146
1147 def seek(self, pos, whence=0):
1148 if not (0 <= whence <= 2):
1149 raise ValueError("invalid whence")
1150 with self._write_lock:
1151 self._flush_unlocked()
1152 return _BufferedIOMixin.seek(self, pos, whence)
1153
1154
1155class BufferedRWPair(BufferedIOBase):
1156
1157 """A buffered reader and writer object together.
1158
1159 A buffered reader object and buffered writer object put together to
1160 form a sequential IO object that can read and write. This is typically
1161 used with a socket or two-way pipe.
1162
1163 reader and writer are RawIOBase objects that are readable and
1164 writeable respectively. If the buffer_size is omitted it defaults to
Benjamin Peterson59406a92009-03-26 17:10:29 +00001165 DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001166 """
1167
1168 # XXX The usefulness of this (compared to having two separate IO
1169 # objects) is questionable.
1170
1171 def __init__(self, reader, writer,
1172 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1173 """Constructor.
1174
1175 The arguments are two RawIO instances.
1176 """
Benjamin Peterson59406a92009-03-26 17:10:29 +00001177 if max_buffer_size is not None:
1178 warnings.warn("max_buffer_size is deprecated", DeprecationWarning, 2)
Antoine Pitroucf4c7492009-04-19 00:09:36 +00001179
1180 if not reader.readable():
1181 raise IOError('"reader" argument must be readable.')
1182
1183 if not writer.writable():
1184 raise IOError('"writer" argument must be writable.')
1185
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001186 self.reader = BufferedReader(reader, buffer_size)
Benjamin Peterson59406a92009-03-26 17:10:29 +00001187 self.writer = BufferedWriter(writer, buffer_size)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001188
1189 def read(self, n=None):
1190 if n is None:
1191 n = -1
1192 return self.reader.read(n)
1193
1194 def readinto(self, b):
1195 return self.reader.readinto(b)
1196
1197 def write(self, b):
1198 return self.writer.write(b)
1199
1200 def peek(self, n=0):
1201 return self.reader.peek(n)
1202
1203 def read1(self, n):
1204 return self.reader.read1(n)
1205
1206 def readable(self):
1207 return self.reader.readable()
1208
1209 def writable(self):
1210 return self.writer.writable()
1211
1212 def flush(self):
1213 return self.writer.flush()
1214
1215 def close(self):
1216 self.writer.close()
1217 self.reader.close()
1218
1219 def isatty(self):
1220 return self.reader.isatty() or self.writer.isatty()
1221
1222 @property
1223 def closed(self):
1224 return self.writer.closed
1225
1226
1227class BufferedRandom(BufferedWriter, BufferedReader):
1228
1229 """A buffered interface to random access streams.
1230
1231 The constructor creates a reader and writer for a seekable stream,
1232 raw, given in the first argument. If the buffer_size is omitted it
Benjamin Peterson59406a92009-03-26 17:10:29 +00001233 defaults to DEFAULT_BUFFER_SIZE.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001234 """
1235
Benjamin Peterson59406a92009-03-26 17:10:29 +00001236 _warning_stack_offset = 3
1237
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001238 def __init__(self, raw,
1239 buffer_size=DEFAULT_BUFFER_SIZE, max_buffer_size=None):
1240 raw._checkSeekable()
1241 BufferedReader.__init__(self, raw, buffer_size)
1242 BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
1243
1244 def seek(self, pos, whence=0):
1245 if not (0 <= whence <= 2):
1246 raise ValueError("invalid whence")
1247 self.flush()
1248 if self._read_buf:
1249 # Undo read ahead.
1250 with self._read_lock:
1251 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1252 # First do the raw seek, then empty the read buffer, so that
1253 # if the raw seek fails, we don't lose buffered data forever.
1254 pos = self.raw.seek(pos, whence)
1255 with self._read_lock:
1256 self._reset_read_buf()
1257 if pos < 0:
1258 raise IOError("seek() returned invalid position")
1259 return pos
1260
1261 def tell(self):
1262 if self._write_buf:
1263 return BufferedWriter.tell(self)
1264 else:
1265 return BufferedReader.tell(self)
1266
1267 def truncate(self, pos=None):
1268 if pos is None:
1269 pos = self.tell()
1270 # Use seek to flush the read buffer.
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001271 return BufferedWriter.truncate(self, pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001272
1273 def read(self, n=None):
1274 if n is None:
1275 n = -1
1276 self.flush()
1277 return BufferedReader.read(self, n)
1278
1279 def readinto(self, b):
1280 self.flush()
1281 return BufferedReader.readinto(self, b)
1282
1283 def peek(self, n=0):
1284 self.flush()
1285 return BufferedReader.peek(self, n)
1286
1287 def read1(self, n):
1288 self.flush()
1289 return BufferedReader.read1(self, n)
1290
1291 def write(self, b):
1292 if self._read_buf:
1293 # Undo readahead
1294 with self._read_lock:
1295 self.raw.seek(self._read_pos - len(self._read_buf), 1)
1296 self._reset_read_buf()
1297 return BufferedWriter.write(self, b)
1298
1299
1300class TextIOBase(IOBase):
1301
1302 """Base class for text I/O.
1303
1304 This class provides a character and line based interface to stream
1305 I/O. There is no readinto method because Python's character strings
1306 are immutable. There is no public constructor.
1307 """
1308
Georg Brandl4d73b572011-01-13 07:13:06 +00001309 def read(self, n=-1):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001310 """Read at most n characters from stream, where n is an int.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001311
1312 Read from underlying buffer until we have n characters or we hit EOF.
1313 If n is negative or omitted, read until EOF.
Raymond Hettingercbb80892011-01-13 18:15:51 +00001314
1315 Returns a string.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001316 """
1317 self._unsupported("read")
1318
Raymond Hettinger3c940242011-01-12 23:39:31 +00001319 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001320 """Write string s to stream and returning an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001321 self._unsupported("write")
1322
Georg Brandl4d73b572011-01-13 07:13:06 +00001323 def truncate(self, pos=None):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001324 """Truncate size to pos, where pos is an int."""
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001325 self._unsupported("truncate")
1326
Raymond Hettinger3c940242011-01-12 23:39:31 +00001327 def readline(self):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001328 """Read until newline or EOF.
1329
1330 Returns an empty string if EOF is hit immediately.
1331 """
1332 self._unsupported("readline")
1333
Raymond Hettinger3c940242011-01-12 23:39:31 +00001334 def detach(self):
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001335 """
1336 Separate the underlying buffer from the TextIOBase and return it.
1337
1338 After the underlying buffer has been detached, the TextIO is in an
1339 unusable state.
1340 """
1341 self._unsupported("detach")
1342
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001343 @property
1344 def encoding(self):
1345 """Subclasses should override."""
1346 return None
1347
1348 @property
1349 def newlines(self):
1350 """Line endings translated so far.
1351
1352 Only line endings translated during reading are considered.
1353
1354 Subclasses should override.
1355 """
1356 return None
1357
Benjamin Peterson0926ad12009-06-06 18:02:12 +00001358 @property
1359 def errors(self):
1360 """Error setting of the decoder or encoder.
1361
1362 Subclasses should override."""
1363 return None
1364
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001365io.TextIOBase.register(TextIOBase)
1366
1367
1368class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
1369 r"""Codec used when reading a file in universal newlines mode. It wraps
1370 another incremental decoder, translating \r\n and \r into \n. It also
1371 records the types of newlines encountered. When used with
1372 translate=False, it ensures that the newline sequence is returned in
1373 one piece.
1374 """
1375 def __init__(self, decoder, translate, errors='strict'):
1376 codecs.IncrementalDecoder.__init__(self, errors=errors)
1377 self.translate = translate
1378 self.decoder = decoder
1379 self.seennl = 0
1380 self.pendingcr = False
1381
1382 def decode(self, input, final=False):
1383 # decode input (with the eventual \r from a previous pass)
1384 if self.decoder is None:
1385 output = input
1386 else:
1387 output = self.decoder.decode(input, final=final)
1388 if self.pendingcr and (output or final):
1389 output = "\r" + output
1390 self.pendingcr = False
1391
1392 # retain last \r even when not translating data:
1393 # then readline() is sure to get \r\n in one pass
1394 if output.endswith("\r") and not final:
1395 output = output[:-1]
1396 self.pendingcr = True
1397
1398 # Record which newlines are read
1399 crlf = output.count('\r\n')
1400 cr = output.count('\r') - crlf
1401 lf = output.count('\n') - crlf
1402 self.seennl |= (lf and self._LF) | (cr and self._CR) \
1403 | (crlf and self._CRLF)
1404
1405 if self.translate:
1406 if crlf:
1407 output = output.replace("\r\n", "\n")
1408 if cr:
1409 output = output.replace("\r", "\n")
1410
1411 return output
1412
1413 def getstate(self):
1414 if self.decoder is None:
1415 buf = b""
1416 flag = 0
1417 else:
1418 buf, flag = self.decoder.getstate()
1419 flag <<= 1
1420 if self.pendingcr:
1421 flag |= 1
1422 return buf, flag
1423
1424 def setstate(self, state):
1425 buf, flag = state
1426 self.pendingcr = bool(flag & 1)
1427 if self.decoder is not None:
1428 self.decoder.setstate((buf, flag >> 1))
1429
1430 def reset(self):
1431 self.seennl = 0
1432 self.pendingcr = False
1433 if self.decoder is not None:
1434 self.decoder.reset()
1435
1436 _LF = 1
1437 _CR = 2
1438 _CRLF = 4
1439
1440 @property
1441 def newlines(self):
1442 return (None,
1443 "\n",
1444 "\r",
1445 ("\r", "\n"),
1446 "\r\n",
1447 ("\n", "\r\n"),
1448 ("\r", "\r\n"),
1449 ("\r", "\n", "\r\n")
1450 )[self.seennl]
1451
1452
1453class TextIOWrapper(TextIOBase):
1454
1455 r"""Character and line based layer over a BufferedIOBase object, buffer.
1456
1457 encoding gives the name of the encoding that the stream will be
1458 decoded or encoded with. It defaults to locale.getpreferredencoding.
1459
1460 errors determines the strictness of encoding and decoding (see the
1461 codecs.register) and defaults to "strict".
1462
1463 newline can be None, '', '\n', '\r', or '\r\n'. It controls the
1464 handling of line endings. If it is None, universal newlines is
1465 enabled. With this enabled, on input, the lines endings '\n', '\r',
1466 or '\r\n' are translated to '\n' before being returned to the
1467 caller. Conversely, on output, '\n' is translated to the system
Éric Araujo39242302011-11-03 00:08:48 +01001468 default line separator, os.linesep. If newline is any other of its
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001469 legal values, that newline becomes the newline when the file is read
1470 and it is returned untranslated. On output, '\n' is converted to the
1471 newline.
1472
1473 If line_buffering is True, a call to flush is implied when a call to
1474 write contains a newline character.
1475 """
1476
1477 _CHUNK_SIZE = 2048
1478
1479 def __init__(self, buffer, encoding=None, errors=None, newline=None,
Antoine Pitroue96ec682011-07-23 21:46:35 +02001480 line_buffering=False, write_through=False):
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001481 if newline is not None and not isinstance(newline, str):
1482 raise TypeError("illegal newline type: %r" % (type(newline),))
1483 if newline not in (None, "", "\n", "\r", "\r\n"):
1484 raise ValueError("illegal newline value: %r" % (newline,))
1485 if encoding is None:
1486 try:
1487 encoding = os.device_encoding(buffer.fileno())
1488 except (AttributeError, UnsupportedOperation):
1489 pass
1490 if encoding is None:
1491 try:
1492 import locale
1493 except ImportError:
1494 # Importing locale may fail if Python is being built
1495 encoding = "ascii"
1496 else:
1497 encoding = locale.getpreferredencoding()
1498
1499 if not isinstance(encoding, str):
1500 raise ValueError("invalid encoding: %r" % encoding)
1501
1502 if errors is None:
1503 errors = "strict"
1504 else:
1505 if not isinstance(errors, str):
1506 raise ValueError("invalid errors: %r" % errors)
1507
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001508 self._buffer = buffer
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001509 self._line_buffering = line_buffering
1510 self._encoding = encoding
1511 self._errors = errors
1512 self._readuniversal = not newline
1513 self._readtranslate = newline is None
1514 self._readnl = newline
1515 self._writetranslate = newline != ''
1516 self._writenl = newline or os.linesep
1517 self._encoder = None
1518 self._decoder = None
1519 self._decoded_chars = '' # buffer for text returned from decoder
1520 self._decoded_chars_used = 0 # offset into _decoded_chars for read()
1521 self._snapshot = None # info for reconstructing decoder state
1522 self._seekable = self._telling = self.buffer.seekable()
Antoine Pitroue96ec682011-07-23 21:46:35 +02001523 self._has_read1 = hasattr(self.buffer, 'read1')
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001524
Antoine Pitroue4501852009-05-14 18:55:55 +00001525 if self._seekable and self.writable():
1526 position = self.buffer.tell()
1527 if position != 0:
1528 try:
1529 self._get_encoder().setstate(0)
1530 except LookupError:
1531 # Sometimes the encoder doesn't exist
1532 pass
1533
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001534 # self._snapshot is either None, or a tuple (dec_flags, next_input)
1535 # where dec_flags is the second (integer) item of the decoder state
1536 # and next_input is the chunk of input bytes that comes next after the
1537 # snapshot point. We use this to reconstruct decoder states in tell().
1538
1539 # Naming convention:
1540 # - "bytes_..." for integer variables that count input bytes
1541 # - "chars_..." for integer variables that count decoded characters
1542
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001543 def __repr__(self):
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001544 result = "<_pyio.TextIOWrapper"
Antoine Pitrou716c4442009-05-23 19:04:03 +00001545 try:
1546 name = self.name
1547 except AttributeError:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001548 pass
Antoine Pitrou716c4442009-05-23 19:04:03 +00001549 else:
Antoine Pitroua4815ca2011-01-09 20:38:15 +00001550 result += " name={0!r}".format(name)
1551 try:
1552 mode = self.mode
1553 except AttributeError:
1554 pass
1555 else:
1556 result += " mode={0!r}".format(mode)
1557 return result + " encoding={0!r}>".format(self.encoding)
Benjamin Petersonc4c0eae2009-03-09 00:07:03 +00001558
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001559 @property
1560 def encoding(self):
1561 return self._encoding
1562
1563 @property
1564 def errors(self):
1565 return self._errors
1566
1567 @property
1568 def line_buffering(self):
1569 return self._line_buffering
1570
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001571 @property
1572 def buffer(self):
1573 return self._buffer
1574
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001575 def seekable(self):
Antoine Pitrou1d857452012-09-05 20:11:49 +02001576 if self.closed:
1577 raise ValueError("I/O operation on closed file.")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001578 return self._seekable
1579
1580 def readable(self):
1581 return self.buffer.readable()
1582
1583 def writable(self):
1584 return self.buffer.writable()
1585
1586 def flush(self):
1587 self.buffer.flush()
1588 self._telling = self._seekable
1589
1590 def close(self):
Antoine Pitrou6be88762010-05-03 16:48:20 +00001591 if self.buffer is not None and not self.closed:
1592 self.flush()
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001593 self.buffer.close()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001594
1595 @property
1596 def closed(self):
1597 return self.buffer.closed
1598
1599 @property
1600 def name(self):
1601 return self.buffer.name
1602
1603 def fileno(self):
1604 return self.buffer.fileno()
1605
1606 def isatty(self):
1607 return self.buffer.isatty()
1608
Raymond Hettinger00fa0392011-01-13 02:52:26 +00001609 def write(self, s):
Raymond Hettingercbb80892011-01-13 18:15:51 +00001610 'Write data, where s is a str'
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001611 if self.closed:
1612 raise ValueError("write to closed file")
1613 if not isinstance(s, str):
1614 raise TypeError("can't write %s to text stream" %
1615 s.__class__.__name__)
1616 length = len(s)
1617 haslf = (self._writetranslate or self._line_buffering) and "\n" in s
1618 if haslf and self._writetranslate and self._writenl != "\n":
1619 s = s.replace("\n", self._writenl)
1620 encoder = self._encoder or self._get_encoder()
1621 # XXX What if we were just reading?
1622 b = encoder.encode(s)
1623 self.buffer.write(b)
1624 if self._line_buffering and (haslf or "\r" in s):
1625 self.flush()
1626 self._snapshot = None
1627 if self._decoder:
1628 self._decoder.reset()
1629 return length
1630
1631 def _get_encoder(self):
1632 make_encoder = codecs.getincrementalencoder(self._encoding)
1633 self._encoder = make_encoder(self._errors)
1634 return self._encoder
1635
1636 def _get_decoder(self):
1637 make_decoder = codecs.getincrementaldecoder(self._encoding)
1638 decoder = make_decoder(self._errors)
1639 if self._readuniversal:
1640 decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
1641 self._decoder = decoder
1642 return decoder
1643
1644 # The following three methods implement an ADT for _decoded_chars.
1645 # Text returned from the decoder is buffered here until the client
1646 # requests it by calling our read() or readline() method.
1647 def _set_decoded_chars(self, chars):
1648 """Set the _decoded_chars buffer."""
1649 self._decoded_chars = chars
1650 self._decoded_chars_used = 0
1651
1652 def _get_decoded_chars(self, n=None):
1653 """Advance into the _decoded_chars buffer."""
1654 offset = self._decoded_chars_used
1655 if n is None:
1656 chars = self._decoded_chars[offset:]
1657 else:
1658 chars = self._decoded_chars[offset:offset + n]
1659 self._decoded_chars_used += len(chars)
1660 return chars
1661
1662 def _rewind_decoded_chars(self, n):
1663 """Rewind the _decoded_chars buffer."""
1664 if self._decoded_chars_used < n:
1665 raise AssertionError("rewind decoded_chars out of bounds")
1666 self._decoded_chars_used -= n
1667
1668 def _read_chunk(self):
1669 """
1670 Read and decode the next chunk of data from the BufferedReader.
1671 """
1672
1673 # The return value is True unless EOF was reached. The decoded
1674 # string is placed in self._decoded_chars (replacing its previous
1675 # value). The entire input chunk is sent to the decoder, though
1676 # some of it may remain buffered in the decoder, yet to be
1677 # converted.
1678
1679 if self._decoder is None:
1680 raise ValueError("no decoder")
1681
1682 if self._telling:
1683 # To prepare for tell(), we need to snapshot a point in the
1684 # file where the decoder's input buffer is empty.
1685
1686 dec_buffer, dec_flags = self._decoder.getstate()
1687 # Given this, we know there was a valid snapshot point
1688 # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
1689
1690 # Read a chunk, decode it, and put the result in self._decoded_chars.
Antoine Pitroue96ec682011-07-23 21:46:35 +02001691 if self._has_read1:
1692 input_chunk = self.buffer.read1(self._CHUNK_SIZE)
1693 else:
1694 input_chunk = self.buffer.read(self._CHUNK_SIZE)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001695 eof = not input_chunk
1696 self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
1697
1698 if self._telling:
1699 # At the snapshot point, len(dec_buffer) bytes before the read,
1700 # the next input to be decoded is dec_buffer + input_chunk.
1701 self._snapshot = (dec_flags, dec_buffer + input_chunk)
1702
1703 return not eof
1704
1705 def _pack_cookie(self, position, dec_flags=0,
1706 bytes_to_feed=0, need_eof=0, chars_to_skip=0):
1707 # The meaning of a tell() cookie is: seek to position, set the
1708 # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
1709 # into the decoder with need_eof as the EOF flag, then skip
1710 # chars_to_skip characters of the decoded result. For most simple
1711 # decoders, tell() will often just give a byte offset in the file.
1712 return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
1713 (chars_to_skip<<192) | bool(need_eof)<<256)
1714
1715 def _unpack_cookie(self, bigint):
1716 rest, position = divmod(bigint, 1<<64)
1717 rest, dec_flags = divmod(rest, 1<<64)
1718 rest, bytes_to_feed = divmod(rest, 1<<64)
1719 need_eof, chars_to_skip = divmod(rest, 1<<64)
1720 return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
1721
1722 def tell(self):
1723 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001724 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001725 if not self._telling:
1726 raise IOError("telling position disabled by next() call")
1727 self.flush()
1728 position = self.buffer.tell()
1729 decoder = self._decoder
1730 if decoder is None or self._snapshot is None:
1731 if self._decoded_chars:
1732 # This should never happen.
1733 raise AssertionError("pending decoded text")
1734 return position
1735
1736 # Skip backward to the snapshot point (see _read_chunk).
1737 dec_flags, next_input = self._snapshot
1738 position -= len(next_input)
1739
1740 # How many decoded characters have been used up since the snapshot?
1741 chars_to_skip = self._decoded_chars_used
1742 if chars_to_skip == 0:
1743 # We haven't moved from the snapshot point.
1744 return self._pack_cookie(position, dec_flags)
1745
1746 # Starting from the snapshot position, we will walk the decoder
1747 # forward until it gives us enough decoded characters.
1748 saved_state = decoder.getstate()
1749 try:
1750 # Note our initial start point.
1751 decoder.setstate((b'', dec_flags))
1752 start_pos = position
1753 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1754 need_eof = 0
1755
1756 # Feed the decoder one byte at a time. As we go, note the
1757 # nearest "safe start point" before the current location
1758 # (a point where the decoder has nothing buffered, so seek()
1759 # can safely start from there and advance to this location).
1760 next_byte = bytearray(1)
1761 for next_byte[0] in next_input:
1762 bytes_fed += 1
1763 chars_decoded += len(decoder.decode(next_byte))
1764 dec_buffer, dec_flags = decoder.getstate()
1765 if not dec_buffer and chars_decoded <= chars_to_skip:
1766 # Decoder buffer is empty, so this is a safe start point.
1767 start_pos += bytes_fed
1768 chars_to_skip -= chars_decoded
1769 start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
1770 if chars_decoded >= chars_to_skip:
1771 break
1772 else:
1773 # We didn't get enough decoded data; signal EOF to get more.
1774 chars_decoded += len(decoder.decode(b'', final=True))
1775 need_eof = 1
1776 if chars_decoded < chars_to_skip:
1777 raise IOError("can't reconstruct logical file position")
1778
1779 # The returned cookie corresponds to the last safe start point.
1780 return self._pack_cookie(
1781 start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
1782 finally:
1783 decoder.setstate(saved_state)
1784
1785 def truncate(self, pos=None):
1786 self.flush()
1787 if pos is None:
1788 pos = self.tell()
Antoine Pitrou905a2ff2010-01-31 22:47:27 +00001789 return self.buffer.truncate(pos)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001790
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001791 def detach(self):
1792 if self.buffer is None:
1793 raise ValueError("buffer is already detached")
1794 self.flush()
Antoine Pitrou7f8f4182010-12-21 21:20:59 +00001795 buffer = self._buffer
1796 self._buffer = None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00001797 return buffer
1798
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001799 def seek(self, cookie, whence=0):
1800 if self.closed:
1801 raise ValueError("tell on closed file")
1802 if not self._seekable:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001803 raise UnsupportedOperation("underlying stream is not seekable")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001804 if whence == 1: # seek relative to current position
1805 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001806 raise UnsupportedOperation("can't do nonzero cur-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001807 # Seeking to the current position should attempt to
1808 # sync the underlying buffer with the current position.
1809 whence = 0
1810 cookie = self.tell()
1811 if whence == 2: # seek relative to end of file
1812 if cookie != 0:
Antoine Pitrou0d739d72010-09-05 23:01:12 +00001813 raise UnsupportedOperation("can't do nonzero end-relative seeks")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001814 self.flush()
1815 position = self.buffer.seek(0, 2)
1816 self._set_decoded_chars('')
1817 self._snapshot = None
1818 if self._decoder:
1819 self._decoder.reset()
1820 return position
1821 if whence != 0:
1822 raise ValueError("invalid whence (%r, should be 0, 1 or 2)" %
1823 (whence,))
1824 if cookie < 0:
1825 raise ValueError("negative seek position %r" % (cookie,))
1826 self.flush()
1827
1828 # The strategy of seek() is to go back to the safe start point
1829 # and replay the effect of read(chars_to_skip) from there.
1830 start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
1831 self._unpack_cookie(cookie)
1832
1833 # Seek back to the safe start point.
1834 self.buffer.seek(start_pos)
1835 self._set_decoded_chars('')
1836 self._snapshot = None
1837
1838 # Restore the decoder to its state from the safe start point.
Benjamin Peterson9363a652009-03-05 00:42:09 +00001839 if cookie == 0 and self._decoder:
1840 self._decoder.reset()
1841 elif self._decoder or dec_flags or chars_to_skip:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001842 self._decoder = self._decoder or self._get_decoder()
1843 self._decoder.setstate((b'', dec_flags))
1844 self._snapshot = (dec_flags, b'')
1845
1846 if chars_to_skip:
1847 # Just like _read_chunk, feed the decoder and save a snapshot.
1848 input_chunk = self.buffer.read(bytes_to_feed)
1849 self._set_decoded_chars(
1850 self._decoder.decode(input_chunk, need_eof))
1851 self._snapshot = (dec_flags, input_chunk)
1852
1853 # Skip chars_to_skip of the decoded characters.
1854 if len(self._decoded_chars) < chars_to_skip:
1855 raise IOError("can't restore logical file position")
1856 self._decoded_chars_used = chars_to_skip
1857
Antoine Pitroue4501852009-05-14 18:55:55 +00001858 # Finally, reset the encoder (merely useful for proper BOM handling)
1859 try:
1860 encoder = self._encoder or self._get_encoder()
1861 except LookupError:
1862 # Sometimes the encoder doesn't exist
1863 pass
1864 else:
1865 if cookie != 0:
1866 encoder.setstate(0)
1867 else:
1868 encoder.reset()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001869 return cookie
1870
1871 def read(self, n=None):
Benjamin Petersona1b49012009-03-31 23:11:32 +00001872 self._checkReadable()
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001873 if n is None:
1874 n = -1
1875 decoder = self._decoder or self._get_decoder()
Florent Xiclunab14930c2010-03-13 15:26:44 +00001876 try:
1877 n.__index__
1878 except AttributeError as err:
1879 raise TypeError("an integer is required") from err
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001880 if n < 0:
1881 # Read everything.
1882 result = (self._get_decoded_chars() +
1883 decoder.decode(self.buffer.read(), final=True))
1884 self._set_decoded_chars('')
1885 self._snapshot = None
1886 return result
1887 else:
1888 # Keep reading chunks until we have n characters to return.
1889 eof = False
1890 result = self._get_decoded_chars(n)
1891 while len(result) < n and not eof:
1892 eof = not self._read_chunk()
1893 result += self._get_decoded_chars(n - len(result))
1894 return result
1895
1896 def __next__(self):
1897 self._telling = False
1898 line = self.readline()
1899 if not line:
1900 self._snapshot = None
1901 self._telling = self._seekable
1902 raise StopIteration
1903 return line
1904
1905 def readline(self, limit=None):
1906 if self.closed:
1907 raise ValueError("read from closed file")
1908 if limit is None:
1909 limit = -1
Benjamin Petersonb01138a2009-04-24 22:59:52 +00001910 elif not isinstance(limit, int):
1911 raise TypeError("limit must be an integer")
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001912
1913 # Grab all the decoded text (we will rewind any extra bits later).
1914 line = self._get_decoded_chars()
1915
1916 start = 0
1917 # Make the decoder if it doesn't already exist.
1918 if not self._decoder:
1919 self._get_decoder()
1920
1921 pos = endpos = None
1922 while True:
1923 if self._readtranslate:
1924 # Newlines are already translated, only search for \n
1925 pos = line.find('\n', start)
1926 if pos >= 0:
1927 endpos = pos + 1
1928 break
1929 else:
1930 start = len(line)
1931
1932 elif self._readuniversal:
1933 # Universal newline search. Find any of \r, \r\n, \n
1934 # The decoder ensures that \r\n are not split in two pieces
1935
1936 # In C we'd look for these in parallel of course.
1937 nlpos = line.find("\n", start)
1938 crpos = line.find("\r", start)
1939 if crpos == -1:
1940 if nlpos == -1:
1941 # Nothing found
1942 start = len(line)
1943 else:
1944 # Found \n
1945 endpos = nlpos + 1
1946 break
1947 elif nlpos == -1:
1948 # Found lone \r
1949 endpos = crpos + 1
1950 break
1951 elif nlpos < crpos:
1952 # Found \n
1953 endpos = nlpos + 1
1954 break
1955 elif nlpos == crpos + 1:
1956 # Found \r\n
1957 endpos = crpos + 2
1958 break
1959 else:
1960 # Found \r
1961 endpos = crpos + 1
1962 break
1963 else:
1964 # non-universal
1965 pos = line.find(self._readnl)
1966 if pos >= 0:
1967 endpos = pos + len(self._readnl)
1968 break
1969
1970 if limit >= 0 and len(line) >= limit:
1971 endpos = limit # reached length limit
1972 break
1973
1974 # No line ending seen yet - get more data'
1975 while self._read_chunk():
1976 if self._decoded_chars:
1977 break
1978 if self._decoded_chars:
1979 line += self._get_decoded_chars()
1980 else:
1981 # end of file
1982 self._set_decoded_chars('')
1983 self._snapshot = None
1984 return line
1985
1986 if limit >= 0 and endpos > limit:
1987 endpos = limit # don't exceed limit
1988
1989 # Rewind _decoded_chars to just after the line ending we found.
1990 self._rewind_decoded_chars(len(line) - endpos)
1991 return line[:endpos]
1992
1993 @property
1994 def newlines(self):
1995 return self._decoder.newlines if self._decoder else None
1996
1997
1998class StringIO(TextIOWrapper):
1999 """Text I/O implementation using an in-memory buffer.
2000
2001 The initial_value argument sets the value of object. The newline
2002 argument is like the one of TextIOWrapper's constructor.
2003 """
2004
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002005 def __init__(self, initial_value="", newline="\n"):
2006 super(StringIO, self).__init__(BytesIO(),
2007 encoding="utf-8",
2008 errors="strict",
2009 newline=newline)
Antoine Pitrou11446482009-04-04 14:09:30 +00002010 # Issue #5645: make universal newlines semantics the same as in the
2011 # C version, even under Windows.
2012 if newline is None:
2013 self._writetranslate = False
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002014 if initial_value is not None:
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002015 if not isinstance(initial_value, str):
Alexandre Vassalottid2bb18b2009-07-22 03:07:33 +00002016 raise TypeError("initial_value must be str or None, not {0}"
2017 .format(type(initial_value).__name__))
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002018 initial_value = str(initial_value)
2019 self.write(initial_value)
2020 self.seek(0)
2021
2022 def getvalue(self):
2023 self.flush()
2024 return self.buffer.getvalue().decode(self._encoding, self._errors)
Benjamin Peterson9fd459a2009-03-09 00:09:44 +00002025
2026 def __repr__(self):
2027 # TextIOWrapper tells the encoding in its repr. In StringIO,
2028 # that's a implementation detail.
2029 return object.__repr__(self)
Benjamin Petersonb487e632009-03-21 03:08:31 +00002030
2031 @property
Benjamin Peterson0926ad12009-06-06 18:02:12 +00002032 def errors(self):
2033 return None
2034
2035 @property
Benjamin Petersonb487e632009-03-21 03:08:31 +00002036 def encoding(self):
2037 return None
Benjamin Petersond2e0c792009-05-01 20:40:59 +00002038
2039 def detach(self):
2040 # This doesn't make sense on StringIO.
2041 self._unsupported("detach")