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