Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 1 | """ codecs -- Python Codec Registry, API and helpers. |
| 2 | |
| 3 | |
| 4 | Written by Marc-Andre Lemburg (mal@lemburg.com). |
| 5 | |
| 6 | (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. |
| 7 | |
Victor Stinner | 272d888 | 2017-06-16 08:59:01 +0200 | [diff] [blame] | 8 | """ |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 9 | |
Victor Stinner | 272d888 | 2017-06-16 08:59:01 +0200 | [diff] [blame] | 10 | import builtins |
| 11 | import sys |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 12 | |
| 13 | ### Registry and builtin stateless codec functions |
| 14 | |
Guido van Rossum | b95de4f | 2000-03-31 17:25:23 +0000 | [diff] [blame] | 15 | try: |
| 16 | from _codecs import * |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 17 | except ImportError as why: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 18 | raise SystemError('Failed to load the builtin codecs: %s' % why) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 19 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 20 | __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 21 | "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE", |
| 22 | "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE", |
Walter Dörwald | 3aeb632 | 2002-09-02 13:14:32 +0000 | [diff] [blame] | 23 | "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE", |
Serhiy Storchaka | de3ee5b | 2014-12-20 17:42:38 +0200 | [diff] [blame] | 24 | "CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder", |
| 25 | "StreamReader", "StreamWriter", |
| 26 | "StreamReaderWriter", "StreamRecoder", |
| 27 | "getencoder", "getdecoder", "getincrementalencoder", |
| 28 | "getincrementaldecoder", "getreader", "getwriter", |
| 29 | "encode", "decode", "iterencode", "iterdecode", |
Walter Dörwald | 3aeb632 | 2002-09-02 13:14:32 +0000 | [diff] [blame] | 30 | "strict_errors", "ignore_errors", "replace_errors", |
| 31 | "xmlcharrefreplace_errors", |
Serhiy Storchaka | 166ebc4 | 2014-11-25 13:57:17 +0200 | [diff] [blame] | 32 | "backslashreplace_errors", "namereplace_errors", |
Walter Dörwald | 3aeb632 | 2002-09-02 13:14:32 +0000 | [diff] [blame] | 33 | "register_error", "lookup_error"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 34 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 35 | ### Constants |
| 36 | |
| 37 | # |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 38 | # Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF) |
| 39 | # and its possible byte string values |
| 40 | # for UTF8/UTF16/UTF32 output and little/big endian machines |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 41 | # |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 42 | |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 43 | # UTF-8 |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 44 | BOM_UTF8 = b'\xef\xbb\xbf' |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 45 | |
| 46 | # UTF-16, little endian |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 47 | BOM_LE = BOM_UTF16_LE = b'\xff\xfe' |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 48 | |
| 49 | # UTF-16, big endian |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 50 | BOM_BE = BOM_UTF16_BE = b'\xfe\xff' |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 51 | |
| 52 | # UTF-32, little endian |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 53 | BOM_UTF32_LE = b'\xff\xfe\x00\x00' |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 54 | |
| 55 | # UTF-32, big endian |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 56 | BOM_UTF32_BE = b'\x00\x00\xfe\xff' |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 57 | |
Marc-André Lemburg | b28de0d | 2002-12-12 17:37:50 +0000 | [diff] [blame] | 58 | if sys.byteorder == 'little': |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 59 | |
Marc-André Lemburg | b28de0d | 2002-12-12 17:37:50 +0000 | [diff] [blame] | 60 | # UTF-16, native endianness |
| 61 | BOM = BOM_UTF16 = BOM_UTF16_LE |
| 62 | |
| 63 | # UTF-32, native endianness |
| 64 | BOM_UTF32 = BOM_UTF32_LE |
| 65 | |
| 66 | else: |
| 67 | |
| 68 | # UTF-16, native endianness |
| 69 | BOM = BOM_UTF16 = BOM_UTF16_BE |
| 70 | |
| 71 | # UTF-32, native endianness |
| 72 | BOM_UTF32 = BOM_UTF32_BE |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 73 | |
| 74 | # Old broken names (don't use in new code) |
| 75 | BOM32_LE = BOM_UTF16_LE |
| 76 | BOM32_BE = BOM_UTF16_BE |
| 77 | BOM64_LE = BOM_UTF32_LE |
| 78 | BOM64_BE = BOM_UTF32_BE |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 79 | |
| 80 | |
| 81 | ### Codec base classes (defining the API) |
| 82 | |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 83 | class CodecInfo(tuple): |
Nick Coghlan | c72e4e6 | 2013-11-22 22:39:36 +1000 | [diff] [blame] | 84 | """Codec details when looking up the codec registry""" |
| 85 | |
| 86 | # Private API to allow Python 3.4 to blacklist the known non-Unicode |
| 87 | # codecs in the standard library. A more general mechanism to |
| 88 | # reliably distinguish test encodings from other codecs will hopefully |
| 89 | # be defined for Python 3.5 |
| 90 | # |
| 91 | # See http://bugs.python.org/issue19619 |
| 92 | _is_text_encoding = True # Assume codecs are text encodings by default |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 93 | |
| 94 | def __new__(cls, encode, decode, streamreader=None, streamwriter=None, |
Nick Coghlan | c72e4e6 | 2013-11-22 22:39:36 +1000 | [diff] [blame] | 95 | incrementalencoder=None, incrementaldecoder=None, name=None, |
| 96 | *, _is_text_encoding=None): |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 97 | self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter)) |
| 98 | self.name = name |
| 99 | self.encode = encode |
| 100 | self.decode = decode |
| 101 | self.incrementalencoder = incrementalencoder |
| 102 | self.incrementaldecoder = incrementaldecoder |
| 103 | self.streamwriter = streamwriter |
| 104 | self.streamreader = streamreader |
Nick Coghlan | c72e4e6 | 2013-11-22 22:39:36 +1000 | [diff] [blame] | 105 | if _is_text_encoding is not None: |
| 106 | self._is_text_encoding = _is_text_encoding |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 107 | return self |
| 108 | |
| 109 | def __repr__(self): |
Serhiy Storchaka | 521e586 | 2014-07-22 15:00:37 +0300 | [diff] [blame] | 110 | return "<%s.%s object for encoding %s at %#x>" % \ |
| 111 | (self.__class__.__module__, self.__class__.__qualname__, |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 112 | self.name, id(self)) |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 113 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 114 | class Codec: |
| 115 | |
| 116 | """ Defines the interface for stateless encoders/decoders. |
| 117 | |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 118 | The .encode()/.decode() methods may use different error |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 119 | handling schemes by providing the errors argument. These |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 120 | string values are predefined: |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 121 | |
Guido van Rossum | d8855fd | 2000-03-24 22:14:19 +0000 | [diff] [blame] | 122 | 'strict' - raise a ValueError error (or a subclass) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 123 | 'ignore' - ignore the character and continue with the next |
| 124 | 'replace' - replace with a suitable replacement character; |
| 125 | Python will use the official U+FFFD REPLACEMENT |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 126 | CHARACTER for the builtin Unicode codecs on |
| 127 | decoding and '?' on encoding. |
Serhiy Storchaka | d3faf43 | 2015-01-18 11:28:37 +0200 | [diff] [blame] | 128 | 'surrogateescape' - replace with private code points U+DCnn. |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 129 | 'xmlcharrefreplace' - Replace with the appropriate XML |
| 130 | character reference (only for encoding). |
Serhiy Storchaka | 07985ef | 2015-01-25 22:56:57 +0200 | [diff] [blame] | 131 | 'backslashreplace' - Replace with backslashed escape sequences. |
| 132 | 'namereplace' - Replace with \\N{...} escape sequences |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 133 | (only for encoding). |
| 134 | |
| 135 | The set of allowed values can be extended via register_error. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 136 | |
| 137 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 138 | def encode(self, input, errors='strict'): |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 139 | |
Fred Drake | 3e74c0d | 2000-03-17 15:40:35 +0000 | [diff] [blame] | 140 | """ Encodes the object input and returns a tuple (output |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 141 | object, length consumed). |
| 142 | |
| 143 | errors defines the error handling to apply. It defaults to |
| 144 | 'strict' handling. |
| 145 | |
| 146 | The method may not store state in the Codec instance. Use |
Berker Peksag | 41ca828 | 2015-07-30 18:26:10 +0300 | [diff] [blame] | 147 | StreamWriter for codecs which have to keep state in order to |
| 148 | make encoding efficient. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 149 | |
| 150 | The encoder must be able to handle zero length input and |
| 151 | return an empty object of the output object type in this |
| 152 | situation. |
| 153 | |
| 154 | """ |
| 155 | raise NotImplementedError |
| 156 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 157 | def decode(self, input, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 158 | |
| 159 | """ Decodes the object input and returns a tuple (output |
| 160 | object, length consumed). |
| 161 | |
| 162 | input must be an object which provides the bf_getreadbuf |
| 163 | buffer slot. Python strings, buffer objects and memory |
| 164 | mapped files are examples of objects providing this slot. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 165 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 166 | errors defines the error handling to apply. It defaults to |
| 167 | 'strict' handling. |
| 168 | |
| 169 | The method may not store state in the Codec instance. Use |
Berker Peksag | 41ca828 | 2015-07-30 18:26:10 +0300 | [diff] [blame] | 170 | StreamReader for codecs which have to keep state in order to |
| 171 | make decoding efficient. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 172 | |
| 173 | The decoder must be able to handle zero length input and |
| 174 | return an empty object of the output object type in this |
| 175 | situation. |
| 176 | |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 177 | """ |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 178 | raise NotImplementedError |
| 179 | |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 180 | class IncrementalEncoder(object): |
| 181 | """ |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 182 | An IncrementalEncoder encodes an input in multiple steps. The input can |
| 183 | be passed piece by piece to the encode() method. The IncrementalEncoder |
| 184 | remembers the state of the encoding process between calls to encode(). |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 185 | """ |
| 186 | def __init__(self, errors='strict'): |
| 187 | """ |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 188 | Creates an IncrementalEncoder instance. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 189 | |
| 190 | The IncrementalEncoder may use different error handling schemes by |
| 191 | providing the errors keyword argument. See the module docstring |
| 192 | for a list of possible values. |
| 193 | """ |
| 194 | self.errors = errors |
| 195 | self.buffer = "" |
| 196 | |
| 197 | def encode(self, input, final=False): |
| 198 | """ |
| 199 | Encodes input and returns the resulting object. |
| 200 | """ |
| 201 | raise NotImplementedError |
| 202 | |
| 203 | def reset(self): |
| 204 | """ |
| 205 | Resets the encoder to the initial state. |
| 206 | """ |
| 207 | |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 208 | def getstate(self): |
| 209 | """ |
| 210 | Return the current state of the encoder. |
| 211 | """ |
| 212 | return 0 |
| 213 | |
| 214 | def setstate(self, state): |
| 215 | """ |
| 216 | Set the current state of the encoder. state must have been |
| 217 | returned by getstate(). |
| 218 | """ |
| 219 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 220 | class BufferedIncrementalEncoder(IncrementalEncoder): |
| 221 | """ |
| 222 | This subclass of IncrementalEncoder can be used as the baseclass for an |
| 223 | incremental encoder if the encoder must keep some of the output in a |
| 224 | buffer between calls to encode(). |
| 225 | """ |
| 226 | def __init__(self, errors='strict'): |
| 227 | IncrementalEncoder.__init__(self, errors) |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 228 | # unencoded input that is kept between calls to encode() |
| 229 | self.buffer = "" |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 230 | |
| 231 | def _buffer_encode(self, input, errors, final): |
| 232 | # Overwrite this method in subclasses: It must encode input |
| 233 | # and return an (output, length consumed) tuple |
| 234 | raise NotImplementedError |
| 235 | |
| 236 | def encode(self, input, final=False): |
| 237 | # encode input (taking the buffer into account) |
| 238 | data = self.buffer + input |
| 239 | (result, consumed) = self._buffer_encode(data, self.errors, final) |
| 240 | # keep unencoded input until the next call |
| 241 | self.buffer = data[consumed:] |
| 242 | return result |
| 243 | |
| 244 | def reset(self): |
| 245 | IncrementalEncoder.reset(self) |
| 246 | self.buffer = "" |
| 247 | |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 248 | def getstate(self): |
| 249 | return self.buffer or 0 |
| 250 | |
| 251 | def setstate(self, state): |
| 252 | self.buffer = state or "" |
| 253 | |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 254 | class IncrementalDecoder(object): |
| 255 | """ |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 256 | An IncrementalDecoder decodes an input in multiple steps. The input can |
| 257 | be passed piece by piece to the decode() method. The IncrementalDecoder |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 258 | remembers the state of the decoding process between calls to decode(). |
| 259 | """ |
| 260 | def __init__(self, errors='strict'): |
| 261 | """ |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 262 | Create an IncrementalDecoder instance. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 263 | |
| 264 | The IncrementalDecoder may use different error handling schemes by |
| 265 | providing the errors keyword argument. See the module docstring |
| 266 | for a list of possible values. |
| 267 | """ |
| 268 | self.errors = errors |
| 269 | |
| 270 | def decode(self, input, final=False): |
| 271 | """ |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 272 | Decode input and returns the resulting object. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 273 | """ |
| 274 | raise NotImplementedError |
| 275 | |
| 276 | def reset(self): |
| 277 | """ |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 278 | Reset the decoder to the initial state. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 279 | """ |
| 280 | |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 281 | def getstate(self): |
| 282 | """ |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 283 | Return the current state of the decoder. |
| 284 | |
| 285 | This must be a (buffered_input, additional_state_info) tuple. |
| 286 | buffered_input must be a bytes object containing bytes that |
| 287 | were passed to decode() that have not yet been converted. |
| 288 | additional_state_info must be a non-negative integer |
| 289 | representing the state of the decoder WITHOUT yet having |
| 290 | processed the contents of buffered_input. In the initial state |
| 291 | and after reset(), getstate() must return (b"", 0). |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 292 | """ |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 293 | return (b"", 0) |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 294 | |
| 295 | def setstate(self, state): |
| 296 | """ |
Ka-Ping Yee | f44c7e8 | 2008-03-18 04:51:32 +0000 | [diff] [blame] | 297 | Set the current state of the decoder. |
| 298 | |
| 299 | state must have been returned by getstate(). The effect of |
| 300 | setstate((b"", 0)) must be equivalent to reset(). |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 301 | """ |
| 302 | |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 303 | class BufferedIncrementalDecoder(IncrementalDecoder): |
| 304 | """ |
| 305 | This subclass of IncrementalDecoder can be used as the baseclass for an |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 306 | incremental decoder if the decoder must be able to handle incomplete |
| 307 | byte sequences. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 308 | """ |
| 309 | def __init__(self, errors='strict'): |
| 310 | IncrementalDecoder.__init__(self, errors) |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 311 | # undecoded input that is kept between calls to decode() |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 312 | self.buffer = b"" |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 313 | |
| 314 | def _buffer_decode(self, input, errors, final): |
| 315 | # Overwrite this method in subclasses: It must decode input |
| 316 | # and return an (output, length consumed) tuple |
| 317 | raise NotImplementedError |
| 318 | |
| 319 | def decode(self, input, final=False): |
| 320 | # decode input (taking the buffer into account) |
| 321 | data = self.buffer + input |
| 322 | (result, consumed) = self._buffer_decode(data, self.errors, final) |
| 323 | # keep undecoded input until the next call |
| 324 | self.buffer = data[consumed:] |
| 325 | return result |
| 326 | |
| 327 | def reset(self): |
| 328 | IncrementalDecoder.reset(self) |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 329 | self.buffer = b"" |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 330 | |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 331 | def getstate(self): |
| 332 | # additional state info is always 0 |
| 333 | return (self.buffer, 0) |
| 334 | |
| 335 | def setstate(self, state): |
| 336 | # ignore additional state info |
| 337 | self.buffer = state[0] |
| 338 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 339 | # |
| 340 | # The StreamWriter and StreamReader class provide generic working |
Andrew M. Kuchling | 97c5635 | 2001-09-18 20:29:48 +0000 | [diff] [blame] | 341 | # interfaces which can be used to implement new encoding submodules |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 342 | # very easily. See encodings/utf_8.py for an example on how this is |
| 343 | # done. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 344 | # |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 345 | |
| 346 | class StreamWriter(Codec): |
| 347 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 348 | def __init__(self, stream, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 349 | |
| 350 | """ Creates a StreamWriter instance. |
| 351 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 352 | stream must be a file-like object open for writing. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 353 | |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 354 | The StreamWriter may use different error handling |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 355 | schemes by providing the errors keyword argument. These |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 356 | parameters are predefined: |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 357 | |
| 358 | 'strict' - raise a ValueError (or a subclass) |
| 359 | 'ignore' - ignore the character and continue with the next |
| 360 | 'replace'- replace with a suitable replacement character |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 361 | 'xmlcharrefreplace' - Replace with the appropriate XML |
| 362 | character reference. |
| 363 | 'backslashreplace' - Replace with backslashed escape |
Serhiy Storchaka | 07985ef | 2015-01-25 22:56:57 +0200 | [diff] [blame] | 364 | sequences. |
| 365 | 'namereplace' - Replace with \\N{...} escape sequences. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 366 | |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 367 | The set of allowed parameter values can be extended via |
| 368 | register_error. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 369 | """ |
| 370 | self.stream = stream |
| 371 | self.errors = errors |
| 372 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 373 | def write(self, object): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 374 | |
| 375 | """ Writes the object's contents encoded to self.stream. |
| 376 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 377 | data, consumed = self.encode(object, self.errors) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 378 | self.stream.write(data) |
| 379 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 380 | def writelines(self, list): |
| 381 | |
| 382 | """ Writes the concatenated list of strings to the stream |
| 383 | using .write(). |
| 384 | """ |
| 385 | self.write(''.join(list)) |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 386 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 387 | def reset(self): |
| 388 | |
| 389 | """ Flushes and resets the codec buffers used for keeping state. |
| 390 | |
| 391 | Calling this method should ensure that the data on the |
| 392 | output is put into a clean state, that allows appending |
| 393 | of new fresh data without having to rescan the whole |
| 394 | stream to recover state. |
| 395 | |
| 396 | """ |
| 397 | pass |
| 398 | |
Victor Stinner | a92ad7e | 2010-05-22 16:59:09 +0000 | [diff] [blame] | 399 | def seek(self, offset, whence=0): |
| 400 | self.stream.seek(offset, whence) |
| 401 | if whence == 0 and offset == 0: |
| 402 | self.reset() |
| 403 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 404 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 405 | getattr=getattr): |
| 406 | |
| 407 | """ Inherit all other methods from the underlying stream. |
| 408 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 409 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 410 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 411 | def __enter__(self): |
| 412 | return self |
| 413 | |
| 414 | def __exit__(self, type, value, tb): |
| 415 | self.stream.close() |
| 416 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 417 | ### |
| 418 | |
| 419 | class StreamReader(Codec): |
| 420 | |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 421 | charbuffertype = str |
| 422 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 423 | def __init__(self, stream, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 424 | |
| 425 | """ Creates a StreamReader instance. |
| 426 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 427 | stream must be a file-like object open for reading. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 428 | |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 429 | The StreamReader may use different error handling |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 430 | schemes by providing the errors keyword argument. These |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 431 | parameters are predefined: |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 432 | |
| 433 | 'strict' - raise a ValueError (or a subclass) |
| 434 | 'ignore' - ignore the character and continue with the next |
Serhiy Storchaka | 07985ef | 2015-01-25 22:56:57 +0200 | [diff] [blame] | 435 | 'replace'- replace with a suitable replacement character |
| 436 | 'backslashreplace' - Replace with backslashed escape sequences; |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 437 | |
Walter Dörwald | 7f82f79 | 2002-11-19 21:42:53 +0000 | [diff] [blame] | 438 | The set of allowed parameter values can be extended via |
| 439 | register_error. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 440 | """ |
| 441 | self.stream = stream |
| 442 | self.errors = errors |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 443 | self.bytebuffer = b"" |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 444 | self._empty_charbuffer = self.charbuffertype() |
| 445 | self.charbuffer = self._empty_charbuffer |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 446 | self.linebuffer = None |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 447 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 448 | def decode(self, input, errors='strict'): |
| 449 | raise NotImplementedError |
| 450 | |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 451 | def read(self, size=-1, chars=-1, firstline=False): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 452 | |
| 453 | """ Decodes data from the stream self.stream and returns the |
| 454 | resulting object. |
| 455 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 456 | chars indicates the number of decoded code points or bytes to |
| 457 | return. read() will never return more data than requested, |
| 458 | but it might return less, if there is not enough available. |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 459 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 460 | size indicates the approximate maximum number of decoded |
| 461 | bytes or code points to read for decoding. The decoder |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 462 | can modify this setting as appropriate. The default value |
| 463 | -1 indicates to read and decode as much as possible. size |
| 464 | is intended to prevent having to decode huge files in one |
| 465 | step. |
| 466 | |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 467 | If firstline is true, and a UnicodeDecodeError happens |
| 468 | after the first line terminator in the input only the first line |
| 469 | will be returned, the rest of the input will be kept until the |
| 470 | next call to read(). |
| 471 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 472 | The method should use a greedy read strategy, meaning that |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 473 | it should read as much data as is allowed within the |
| 474 | definition of the encoding and the given size, e.g. if |
| 475 | optional encoding endings or state markers are available |
| 476 | on the stream, these should be read too. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 477 | """ |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 478 | # If we have lines cached, first merge them back into characters |
| 479 | if self.linebuffer: |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 480 | self.charbuffer = self._empty_charbuffer.join(self.linebuffer) |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 481 | self.linebuffer = None |
Tim Peters | 536cf99 | 2005-12-25 23:18:31 +0000 | [diff] [blame] | 482 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 483 | # read until we get the required number of characters (if available) |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 484 | while True: |
Tim Golden | 621302c | 2012-10-01 16:40:40 +0100 | [diff] [blame] | 485 | # can the request be satisfied from the character buffer? |
Serhiy Storchaka | dbe0982 | 2014-01-26 19:27:56 +0200 | [diff] [blame] | 486 | if chars >= 0: |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 487 | if len(self.charbuffer) >= chars: |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 488 | break |
Serhiy Storchaka | dbe0982 | 2014-01-26 19:27:56 +0200 | [diff] [blame] | 489 | elif size >= 0: |
| 490 | if len(self.charbuffer) >= size: |
| 491 | break |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 492 | # we need more data |
| 493 | if size < 0: |
| 494 | newdata = self.stream.read() |
| 495 | else: |
| 496 | newdata = self.stream.read(size) |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 497 | # decode bytes (those remaining from the last call included) |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 498 | data = self.bytebuffer + newdata |
Serhiy Storchaka | dbe0982 | 2014-01-26 19:27:56 +0200 | [diff] [blame] | 499 | if not data: |
| 500 | break |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 501 | try: |
| 502 | newchars, decodedbytes = self.decode(data, self.errors) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 503 | except UnicodeDecodeError as exc: |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 504 | if firstline: |
Walter Dörwald | 3abcb01 | 2007-04-16 22:10:50 +0000 | [diff] [blame] | 505 | newchars, decodedbytes = \ |
| 506 | self.decode(data[:exc.start], self.errors) |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 507 | lines = newchars.splitlines(keepends=True) |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 508 | if len(lines)<=1: |
| 509 | raise |
| 510 | else: |
| 511 | raise |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 512 | # keep undecoded bytes until the next call |
| 513 | self.bytebuffer = data[decodedbytes:] |
| 514 | # put new characters in the character buffer |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 515 | self.charbuffer += newchars |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 516 | # there was no data available |
| 517 | if not newdata: |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 518 | break |
| 519 | if chars < 0: |
| 520 | # Return everything we've got |
| 521 | result = self.charbuffer |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 522 | self.charbuffer = self._empty_charbuffer |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 523 | else: |
| 524 | # Return the first chars characters |
| 525 | result = self.charbuffer[:chars] |
| 526 | self.charbuffer = self.charbuffer[chars:] |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 527 | return result |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 528 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 529 | def readline(self, size=None, keepends=True): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 530 | |
| 531 | """ Read one line from the input stream and return the |
| 532 | decoded data. |
| 533 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 534 | size, if given, is passed as size argument to the |
| 535 | read() method. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 536 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 537 | """ |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 538 | # If we have lines cached from an earlier read, return |
| 539 | # them unconditionally |
| 540 | if self.linebuffer: |
| 541 | line = self.linebuffer[0] |
| 542 | del self.linebuffer[0] |
| 543 | if len(self.linebuffer) == 1: |
| 544 | # revert to charbuffer mode; we might need more data |
| 545 | # next time |
| 546 | self.charbuffer = self.linebuffer[0] |
| 547 | self.linebuffer = None |
| 548 | if not keepends: |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 549 | line = line.splitlines(keepends=False)[0] |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 550 | return line |
Tim Peters | 536cf99 | 2005-12-25 23:18:31 +0000 | [diff] [blame] | 551 | |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 552 | readsize = size or 72 |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 553 | line = self._empty_charbuffer |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 554 | # If size is given, we call read() only once |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 555 | while True: |
Martin v. Löwis | 56066d2 | 2005-08-24 07:38:12 +0000 | [diff] [blame] | 556 | data = self.read(readsize, firstline=True) |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 557 | if data: |
Walter Dörwald | a4eb2d5 | 2005-04-21 21:42:35 +0000 | [diff] [blame] | 558 | # If we're at a "\r" read one extra character (which might |
| 559 | # be a "\n") to get a proper line ending. If the stream is |
Walter Dörwald | bc8e642 | 2005-04-21 21:32:03 +0000 | [diff] [blame] | 560 | # temporarily exhausted we return the wrong line ending. |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 561 | if (isinstance(data, str) and data.endswith("\r")) or \ |
| 562 | (isinstance(data, bytes) and data.endswith(b"\r")): |
Walter Dörwald | 7a6dc13 | 2005-04-04 21:38:47 +0000 | [diff] [blame] | 563 | data += self.read(size=1, chars=1) |
Walter Dörwald | 7a6dc13 | 2005-04-04 21:38:47 +0000 | [diff] [blame] | 564 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 565 | line += data |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 566 | lines = line.splitlines(keepends=True) |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 567 | if lines: |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 568 | if len(lines) > 1: |
| 569 | # More than one line result; the first line is a full line |
| 570 | # to return |
| 571 | line = lines[0] |
| 572 | del lines[0] |
| 573 | if len(lines) > 1: |
| 574 | # cache the remaining lines |
| 575 | lines[-1] += self.charbuffer |
| 576 | self.linebuffer = lines |
| 577 | self.charbuffer = None |
| 578 | else: |
| 579 | # only one remaining line, put it back into charbuffer |
| 580 | self.charbuffer = lines[0] + self.charbuffer |
| 581 | if not keepends: |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 582 | line = line.splitlines(keepends=False)[0] |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 583 | break |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 584 | line0withend = lines[0] |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 585 | line0withoutend = lines[0].splitlines(keepends=False)[0] |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 586 | if line0withend != line0withoutend: # We really have a line end |
| 587 | # Put the rest back together and keep it until the next call |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 588 | self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \ |
| 589 | self.charbuffer |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 590 | if keepends: |
| 591 | line = line0withend |
| 592 | else: |
| 593 | line = line0withoutend |
Walter Dörwald | 9fa0946 | 2005-01-10 12:01:39 +0000 | [diff] [blame] | 594 | break |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 595 | # we didn't get anything or this was our only try |
Walter Dörwald | 9fa0946 | 2005-01-10 12:01:39 +0000 | [diff] [blame] | 596 | if not data or size is not None: |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 597 | if line and not keepends: |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 598 | line = line.splitlines(keepends=False)[0] |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 599 | break |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 600 | if readsize < 8000: |
Walter Dörwald | e57d7b1 | 2004-12-21 22:24:00 +0000 | [diff] [blame] | 601 | readsize *= 2 |
| 602 | return line |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 603 | |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 604 | def readlines(self, sizehint=None, keepends=True): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 605 | |
| 606 | """ Read all lines available on the input stream |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 607 | and return them as a list. |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 608 | |
| 609 | Line breaks are implemented using the codec's decoder |
| 610 | method and are included in the list entries. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 611 | |
Marc-André Lemburg | d594849 | 2004-02-26 15:22:17 +0000 | [diff] [blame] | 612 | sizehint, if given, is ignored since there is no efficient |
| 613 | way to finding the true end-of-line. |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 614 | |
| 615 | """ |
Walter Dörwald | 6965203 | 2004-09-07 20:24:22 +0000 | [diff] [blame] | 616 | data = self.read() |
Hye-Shik Chang | af5c7cf | 2004-10-17 23:51:21 +0000 | [diff] [blame] | 617 | return data.splitlines(keepends) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 618 | |
| 619 | def reset(self): |
| 620 | |
| 621 | """ Resets the codec buffers used for keeping state. |
| 622 | |
| 623 | Note that no stream repositioning should take place. |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 624 | This method is primarily intended to be able to recover |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 625 | from decoding errors. |
| 626 | |
| 627 | """ |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 628 | self.bytebuffer = b"" |
Georg Brandl | 0252462 | 2010-12-02 18:06:51 +0000 | [diff] [blame] | 629 | self.charbuffer = self._empty_charbuffer |
Martin v. Löwis | 4ed6738 | 2005-09-18 08:34:39 +0000 | [diff] [blame] | 630 | self.linebuffer = None |
Walter Dörwald | 729c31f | 2005-03-14 19:06:30 +0000 | [diff] [blame] | 631 | |
Walter Dörwald | 71fd90d | 2005-03-14 19:25:41 +0000 | [diff] [blame] | 632 | def seek(self, offset, whence=0): |
Walter Dörwald | 729c31f | 2005-03-14 19:06:30 +0000 | [diff] [blame] | 633 | """ Set the input stream's current position. |
| 634 | |
| 635 | Resets the codec buffers used for keeping state. |
| 636 | """ |
Walter Dörwald | 729c31f | 2005-03-14 19:06:30 +0000 | [diff] [blame] | 637 | self.stream.seek(offset, whence) |
Victor Stinner | a92ad7e | 2010-05-22 16:59:09 +0000 | [diff] [blame] | 638 | self.reset() |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 639 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 640 | def __next__(self): |
Walter Dörwald | 4dbf192 | 2002-11-06 16:53:44 +0000 | [diff] [blame] | 641 | |
| 642 | """ Return the next decoded line from the input stream.""" |
| 643 | line = self.readline() |
| 644 | if line: |
| 645 | return line |
| 646 | raise StopIteration |
| 647 | |
| 648 | def __iter__(self): |
| 649 | return self |
| 650 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 651 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 652 | getattr=getattr): |
| 653 | |
| 654 | """ Inherit all other methods from the underlying stream. |
| 655 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 656 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 657 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 658 | def __enter__(self): |
| 659 | return self |
| 660 | |
| 661 | def __exit__(self, type, value, tb): |
| 662 | self.stream.close() |
| 663 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 664 | ### |
| 665 | |
| 666 | class StreamReaderWriter: |
| 667 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 668 | """ StreamReaderWriter instances allow wrapping streams which |
| 669 | work in both read and write modes. |
| 670 | |
| 671 | The design is such that one can use the factory functions |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 672 | returned by the codec.lookup() function to construct the |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 673 | instance. |
| 674 | |
| 675 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 676 | # Optional attributes set by the file wrappers below |
| 677 | encoding = 'unknown' |
| 678 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 679 | def __init__(self, stream, Reader, Writer, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 680 | |
| 681 | """ Creates a StreamReaderWriter instance. |
| 682 | |
| 683 | stream must be a Stream-like object. |
| 684 | |
| 685 | Reader, Writer must be factory functions or classes |
| 686 | providing the StreamReader, StreamWriter interface resp. |
| 687 | |
| 688 | Error handling is done in the same way as defined for the |
| 689 | StreamWriter/Readers. |
| 690 | |
| 691 | """ |
| 692 | self.stream = stream |
| 693 | self.reader = Reader(stream, errors) |
| 694 | self.writer = Writer(stream, errors) |
| 695 | self.errors = errors |
| 696 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 697 | def read(self, size=-1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 698 | |
| 699 | return self.reader.read(size) |
| 700 | |
Guido van Rossum | d58c26f | 2000-05-01 16:17:32 +0000 | [diff] [blame] | 701 | def readline(self, size=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 702 | |
| 703 | return self.reader.readline(size) |
| 704 | |
Guido van Rossum | d58c26f | 2000-05-01 16:17:32 +0000 | [diff] [blame] | 705 | def readlines(self, sizehint=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 706 | |
| 707 | return self.reader.readlines(sizehint) |
| 708 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 709 | def __next__(self): |
Walter Dörwald | 4dbf192 | 2002-11-06 16:53:44 +0000 | [diff] [blame] | 710 | |
| 711 | """ Return the next decoded line from the input stream.""" |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 712 | return next(self.reader) |
Walter Dörwald | 4dbf192 | 2002-11-06 16:53:44 +0000 | [diff] [blame] | 713 | |
| 714 | def __iter__(self): |
| 715 | return self |
| 716 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 717 | def write(self, data): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 718 | |
| 719 | return self.writer.write(data) |
| 720 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 721 | def writelines(self, list): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 722 | |
| 723 | return self.writer.writelines(list) |
| 724 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 725 | def reset(self): |
| 726 | |
| 727 | self.reader.reset() |
| 728 | self.writer.reset() |
| 729 | |
Victor Stinner | 3fed087 | 2010-05-22 02:16:27 +0000 | [diff] [blame] | 730 | def seek(self, offset, whence=0): |
Victor Stinner | a92ad7e | 2010-05-22 16:59:09 +0000 | [diff] [blame] | 731 | self.stream.seek(offset, whence) |
| 732 | self.reader.reset() |
| 733 | if whence == 0 and offset == 0: |
| 734 | self.writer.reset() |
Victor Stinner | 3fed087 | 2010-05-22 02:16:27 +0000 | [diff] [blame] | 735 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 736 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 737 | getattr=getattr): |
| 738 | |
| 739 | """ Inherit all other methods from the underlying stream. |
| 740 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 741 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 742 | |
Victor Stinner | 272d888 | 2017-06-16 08:59:01 +0200 | [diff] [blame] | 743 | # these are needed to make "with StreamReaderWriter(...)" work properly |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 744 | |
| 745 | def __enter__(self): |
| 746 | return self |
| 747 | |
| 748 | def __exit__(self, type, value, tb): |
| 749 | self.stream.close() |
| 750 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 751 | ### |
| 752 | |
| 753 | class StreamRecoder: |
| 754 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 755 | """ StreamRecoder instances translate data from one encoding to another. |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 756 | |
| 757 | They use the complete set of APIs returned by the |
| 758 | codecs.lookup() function to implement their task. |
| 759 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 760 | Data written to the StreamRecoder is first decoded into an |
| 761 | intermediate format (depending on the "decode" codec) and then |
| 762 | written to the underlying stream using an instance of the provided |
| 763 | Writer class. |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 764 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 765 | In the other direction, data is read from the underlying stream using |
| 766 | a Reader instance and then encoded and returned to the caller. |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 767 | |
| 768 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 769 | # Optional attributes set by the file wrappers below |
| 770 | data_encoding = 'unknown' |
| 771 | file_encoding = 'unknown' |
| 772 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 773 | def __init__(self, stream, encode, decode, Reader, Writer, |
| 774 | errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 775 | |
| 776 | """ Creates a StreamRecoder instance which implements a two-way |
| 777 | conversion: encode and decode work on the frontend (the |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 778 | data visible to .read() and .write()) while Reader and Writer |
| 779 | work on the backend (the data in stream). |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 780 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 781 | You can use these objects to do transparent |
| 782 | transcodings from e.g. latin-1 to utf-8 and back. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 783 | |
| 784 | stream must be a file-like object. |
| 785 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 786 | encode and decode must adhere to the Codec interface; Reader and |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 787 | Writer must be factory functions or classes providing the |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 788 | StreamReader and StreamWriter interfaces resp. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 789 | |
| 790 | Error handling is done in the same way as defined for the |
| 791 | StreamWriter/Readers. |
| 792 | |
| 793 | """ |
| 794 | self.stream = stream |
| 795 | self.encode = encode |
| 796 | self.decode = decode |
| 797 | self.reader = Reader(stream, errors) |
| 798 | self.writer = Writer(stream, errors) |
| 799 | self.errors = errors |
| 800 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 801 | def read(self, size=-1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 802 | |
| 803 | data = self.reader.read(size) |
| 804 | data, bytesencoded = self.encode(data, self.errors) |
| 805 | return data |
| 806 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 807 | def readline(self, size=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 808 | |
| 809 | if size is None: |
| 810 | data = self.reader.readline() |
| 811 | else: |
| 812 | data = self.reader.readline(size) |
| 813 | data, bytesencoded = self.encode(data, self.errors) |
| 814 | return data |
| 815 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 816 | def readlines(self, sizehint=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 817 | |
Marc-André Lemburg | d594849 | 2004-02-26 15:22:17 +0000 | [diff] [blame] | 818 | data = self.reader.read() |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 819 | data, bytesencoded = self.encode(data, self.errors) |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 820 | return data.splitlines(keepends=True) |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 821 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 822 | def __next__(self): |
Walter Dörwald | 4dbf192 | 2002-11-06 16:53:44 +0000 | [diff] [blame] | 823 | |
| 824 | """ Return the next decoded line from the input stream.""" |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 825 | data = next(self.reader) |
Walter Dörwald | c5238b8 | 2005-09-01 11:56:53 +0000 | [diff] [blame] | 826 | data, bytesencoded = self.encode(data, self.errors) |
| 827 | return data |
Walter Dörwald | 4dbf192 | 2002-11-06 16:53:44 +0000 | [diff] [blame] | 828 | |
| 829 | def __iter__(self): |
| 830 | return self |
| 831 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 832 | def write(self, data): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 833 | |
| 834 | data, bytesdecoded = self.decode(data, self.errors) |
| 835 | return self.writer.write(data) |
| 836 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 837 | def writelines(self, list): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 838 | |
| 839 | data = ''.join(list) |
| 840 | data, bytesdecoded = self.decode(data, self.errors) |
| 841 | return self.writer.write(data) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 842 | |
| 843 | def reset(self): |
| 844 | |
| 845 | self.reader.reset() |
| 846 | self.writer.reset() |
| 847 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 848 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 849 | getattr=getattr): |
| 850 | |
| 851 | """ Inherit all other methods from the underlying stream. |
| 852 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 853 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 854 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 855 | def __enter__(self): |
| 856 | return self |
| 857 | |
| 858 | def __exit__(self, type, value, tb): |
| 859 | self.stream.close() |
| 860 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 861 | ### Shortcuts |
| 862 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 863 | def open(filename, mode='r', encoding=None, errors='strict', buffering=1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 864 | |
| 865 | """ Open an encoded file using the given mode and return |
| 866 | a wrapped version providing transparent encoding/decoding. |
| 867 | |
| 868 | Note: The wrapped version will only accept the object format |
| 869 | defined by the codecs, i.e. Unicode objects for most builtin |
Skip Montanaro | 9f5f9d9 | 2005-03-16 03:51:56 +0000 | [diff] [blame] | 870 | codecs. Output is also codec dependent and will usually be |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 871 | Unicode as well. |
| 872 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 873 | Underlying encoded files are always opened in binary mode. |
| 874 | The default file mode is 'r', meaning to open the file in read mode. |
Marc-André Lemburg | 349a3d3 | 2000-06-21 21:21:04 +0000 | [diff] [blame] | 875 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 876 | encoding specifies the encoding which is to be used for the |
Walter Dörwald | 7f3ed74 | 2003-02-02 23:08:27 +0000 | [diff] [blame] | 877 | file. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 878 | |
| 879 | errors may be given to define the error handling. It defaults |
| 880 | to 'strict' which causes ValueErrors to be raised in case an |
| 881 | encoding error occurs. |
| 882 | |
| 883 | buffering has the same meaning as for the builtin open() API. |
| 884 | It defaults to line buffered. |
| 885 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 886 | The returned wrapped file object provides an extra attribute |
| 887 | .encoding which allows querying the used encoding. This |
| 888 | attribute is only available if an encoding was specified as |
| 889 | parameter. |
| 890 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 891 | """ |
| 892 | if encoding is not None and \ |
| 893 | 'b' not in mode: |
| 894 | # Force opening of the file in binary mode |
| 895 | mode = mode + 'b' |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 896 | file = builtins.open(filename, mode, buffering) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 897 | if encoding is None: |
| 898 | return file |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 899 | info = lookup(encoding) |
| 900 | srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors) |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 901 | # Add attributes to simplify introspection |
| 902 | srw.encoding = encoding |
| 903 | return srw |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 904 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 905 | def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 906 | |
| 907 | """ Return a wrapped version of file which provides transparent |
| 908 | encoding translation. |
| 909 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 910 | Data written to the wrapped file is decoded according |
| 911 | to the given data_encoding and then encoded to the underlying |
| 912 | file using file_encoding. The intermediate data type |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 913 | will usually be Unicode but depends on the specified codecs. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 914 | |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 915 | Bytes read from the file are decoded using file_encoding and then |
| 916 | passed back to the caller encoded using data_encoding. |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 917 | |
| 918 | If file_encoding is not given, it defaults to data_encoding. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 919 | |
| 920 | errors may be given to define the error handling. It defaults |
| 921 | to 'strict' which causes ValueErrors to be raised in case an |
| 922 | encoding error occurs. |
| 923 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 924 | The returned wrapped file object provides two extra attributes |
| 925 | .data_encoding and .file_encoding which reflect the given |
| 926 | parameters of the same name. The attributes can be used for |
| 927 | introspection by Python programs. |
| 928 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 929 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 930 | if file_encoding is None: |
| 931 | file_encoding = data_encoding |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 932 | data_info = lookup(data_encoding) |
| 933 | file_info = lookup(file_encoding) |
| 934 | sr = StreamRecoder(file, data_info.encode, data_info.decode, |
| 935 | file_info.streamreader, file_info.streamwriter, errors) |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 936 | # Add attributes to simplify introspection |
| 937 | sr.data_encoding = data_encoding |
| 938 | sr.file_encoding = file_encoding |
| 939 | return sr |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 940 | |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 941 | ### Helpers for codec lookup |
| 942 | |
| 943 | def getencoder(encoding): |
| 944 | |
| 945 | """ Lookup up the codec for the given encoding and return |
| 946 | its encoder function. |
| 947 | |
| 948 | Raises a LookupError in case the encoding cannot be found. |
| 949 | |
| 950 | """ |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 951 | return lookup(encoding).encode |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 952 | |
| 953 | def getdecoder(encoding): |
| 954 | |
| 955 | """ Lookup up the codec for the given encoding and return |
| 956 | its decoder function. |
| 957 | |
| 958 | Raises a LookupError in case the encoding cannot be found. |
| 959 | |
| 960 | """ |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 961 | return lookup(encoding).decode |
| 962 | |
| 963 | def getincrementalencoder(encoding): |
| 964 | |
| 965 | """ Lookup up the codec for the given encoding and return |
| 966 | its IncrementalEncoder class or factory function. |
| 967 | |
| 968 | Raises a LookupError in case the encoding cannot be found |
| 969 | or the codecs doesn't provide an incremental encoder. |
| 970 | |
| 971 | """ |
| 972 | encoder = lookup(encoding).incrementalencoder |
| 973 | if encoder is None: |
| 974 | raise LookupError(encoding) |
| 975 | return encoder |
| 976 | |
| 977 | def getincrementaldecoder(encoding): |
| 978 | |
| 979 | """ Lookup up the codec for the given encoding and return |
| 980 | its IncrementalDecoder class or factory function. |
| 981 | |
| 982 | Raises a LookupError in case the encoding cannot be found |
| 983 | or the codecs doesn't provide an incremental decoder. |
| 984 | |
| 985 | """ |
| 986 | decoder = lookup(encoding).incrementaldecoder |
| 987 | if decoder is None: |
| 988 | raise LookupError(encoding) |
| 989 | return decoder |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 990 | |
| 991 | def getreader(encoding): |
| 992 | |
| 993 | """ Lookup up the codec for the given encoding and return |
| 994 | its StreamReader class or factory function. |
| 995 | |
| 996 | Raises a LookupError in case the encoding cannot be found. |
| 997 | |
| 998 | """ |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 999 | return lookup(encoding).streamreader |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 1000 | |
| 1001 | def getwriter(encoding): |
| 1002 | |
| 1003 | """ Lookup up the codec for the given encoding and return |
| 1004 | its StreamWriter class or factory function. |
| 1005 | |
| 1006 | Raises a LookupError in case the encoding cannot be found. |
| 1007 | |
| 1008 | """ |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1009 | return lookup(encoding).streamwriter |
| 1010 | |
| 1011 | def iterencode(iterator, encoding, errors='strict', **kwargs): |
| 1012 | """ |
| 1013 | Encoding iterator. |
| 1014 | |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 1015 | Encodes the input strings from the iterator using an IncrementalEncoder. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1016 | |
| 1017 | errors and kwargs are passed through to the IncrementalEncoder |
| 1018 | constructor. |
| 1019 | """ |
| 1020 | encoder = getincrementalencoder(encoding)(errors, **kwargs) |
| 1021 | for input in iterator: |
| 1022 | output = encoder.encode(input) |
| 1023 | if output: |
| 1024 | yield output |
| 1025 | output = encoder.encode("", True) |
| 1026 | if output: |
| 1027 | yield output |
| 1028 | |
| 1029 | def iterdecode(iterator, encoding, errors='strict', **kwargs): |
| 1030 | """ |
| 1031 | Decoding iterator. |
| 1032 | |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 1033 | Decodes the input strings from the iterator using an IncrementalDecoder. |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1034 | |
| 1035 | errors and kwargs are passed through to the IncrementalDecoder |
| 1036 | constructor. |
| 1037 | """ |
| 1038 | decoder = getincrementaldecoder(encoding)(errors, **kwargs) |
| 1039 | for input in iterator: |
| 1040 | output = decoder.decode(input) |
| 1041 | if output: |
| 1042 | yield output |
Walter Dörwald | ca8a8d0 | 2007-05-04 13:05:09 +0000 | [diff] [blame] | 1043 | output = decoder.decode(b"", True) |
Thomas Wouters | a977329 | 2006-04-21 09:43:23 +0000 | [diff] [blame] | 1044 | if output: |
| 1045 | yield output |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 1046 | |
Marc-André Lemburg | a866df8 | 2001-01-03 21:29:14 +0000 | [diff] [blame] | 1047 | ### Helpers for charmap-based codecs |
| 1048 | |
| 1049 | def make_identity_dict(rng): |
| 1050 | |
| 1051 | """ make_identity_dict(rng) -> dict |
| 1052 | |
| 1053 | Return a dictionary where elements of the rng sequence are |
| 1054 | mapped to themselves. |
Tim Peters | 88869f9 | 2001-01-14 23:36:06 +0000 | [diff] [blame] | 1055 | |
Marc-André Lemburg | a866df8 | 2001-01-03 21:29:14 +0000 | [diff] [blame] | 1056 | """ |
Antoine Pitrou | aaefac7 | 2012-06-16 22:48:21 +0200 | [diff] [blame] | 1057 | return {i:i for i in rng} |
Marc-André Lemburg | a866df8 | 2001-01-03 21:29:14 +0000 | [diff] [blame] | 1058 | |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 1059 | def make_encoding_map(decoding_map): |
| 1060 | |
| 1061 | """ Creates an encoding map from a decoding map. |
| 1062 | |
Walter Dörwald | 7f3ed74 | 2003-02-02 23:08:27 +0000 | [diff] [blame] | 1063 | If a target mapping in the decoding map occurs multiple |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 1064 | times, then that target is mapped to None (undefined mapping), |
| 1065 | causing an exception when encountered by the charmap codec |
| 1066 | during translation. |
| 1067 | |
| 1068 | One example where this happens is cp875.py which decodes |
Serhiy Storchaka | 9f8a891 | 2015-04-03 18:12:41 +0300 | [diff] [blame] | 1069 | multiple character to \\u001a. |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 1070 | |
| 1071 | """ |
| 1072 | m = {} |
| 1073 | for k,v in decoding_map.items(): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1074 | if not v in m: |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 1075 | m[v] = k |
| 1076 | else: |
| 1077 | m[v] = None |
| 1078 | return m |
Tim Peters | 3a2ab1a | 2001-05-29 06:06:54 +0000 | [diff] [blame] | 1079 | |
Walter Dörwald | 3aeb632 | 2002-09-02 13:14:32 +0000 | [diff] [blame] | 1080 | ### error handlers |
| 1081 | |
Martin v. Löwis | e2713be | 2005-03-08 15:03:08 +0000 | [diff] [blame] | 1082 | try: |
| 1083 | strict_errors = lookup_error("strict") |
| 1084 | ignore_errors = lookup_error("ignore") |
| 1085 | replace_errors = lookup_error("replace") |
| 1086 | xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace") |
| 1087 | backslashreplace_errors = lookup_error("backslashreplace") |
Serhiy Storchaka | 166ebc4 | 2014-11-25 13:57:17 +0200 | [diff] [blame] | 1088 | namereplace_errors = lookup_error("namereplace") |
Martin v. Löwis | e2713be | 2005-03-08 15:03:08 +0000 | [diff] [blame] | 1089 | except LookupError: |
| 1090 | # In --disable-unicode builds, these error handler are missing |
| 1091 | strict_errors = None |
| 1092 | ignore_errors = None |
| 1093 | replace_errors = None |
| 1094 | xmlcharrefreplace_errors = None |
| 1095 | backslashreplace_errors = None |
Serhiy Storchaka | 166ebc4 | 2014-11-25 13:57:17 +0200 | [diff] [blame] | 1096 | namereplace_errors = None |
Walter Dörwald | 3aeb632 | 2002-09-02 13:14:32 +0000 | [diff] [blame] | 1097 | |
Martin v. Löwis | 6cd441d | 2001-07-31 08:54:55 +0000 | [diff] [blame] | 1098 | # Tell modulefinder that using codecs probably needs the encodings |
| 1099 | # package |
| 1100 | _false = 0 |
| 1101 | if _false: |
| 1102 | import encodings |
| 1103 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 1104 | ### Tests |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 1105 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 1106 | if __name__ == '__main__': |
| 1107 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 1108 | # Make stdout translate Latin-1 output into UTF-8 output |
| 1109 | sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8') |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 1110 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 1111 | # Have stdin translate Latin-1 input into UTF-8 input |
| 1112 | sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1') |