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 | |
Martin v. Löwis | 02d893c | 2001-08-02 07:15:29 +0000 | [diff] [blame] | 10 | import struct, __builtin__ |
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", |
| 23 | "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 24 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 25 | ### Constants |
| 26 | |
| 27 | # |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 28 | # Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF) |
| 29 | # and its possible byte string values |
| 30 | # for UTF8/UTF16/UTF32 output and little/big endian machines |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 31 | # |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 32 | |
Walter Dörwald | 474458d | 2002-06-04 15:16:29 +0000 | [diff] [blame] | 33 | # UTF-8 |
| 34 | BOM_UTF8 = '\xef\xbb\xbf' |
| 35 | |
| 36 | # UTF-16, little endian |
| 37 | BOM_LE = BOM_UTF16_LE = '\xff\xfe' |
| 38 | |
| 39 | # UTF-16, big endian |
| 40 | BOM_BE = BOM_UTF16_BE = '\xfe\xff' |
| 41 | |
| 42 | # UTF-32, little endian |
| 43 | BOM_UTF32_LE = '\xff\xfe\x00\x00' |
| 44 | |
| 45 | # UTF-32, big endian |
| 46 | BOM_UTF32_BE = '\x00\x00\xfe\xff' |
| 47 | |
| 48 | # UTF-16, native endianness |
| 49 | BOM = BOM_UTF16 = struct.pack('=H', 0xFEFF) |
| 50 | |
| 51 | # UTF-32, native endianness |
| 52 | BOM_UTF32 = struct.pack('=L', 0x0000FEFF) |
| 53 | |
| 54 | # Old broken names (don't use in new code) |
| 55 | BOM32_LE = BOM_UTF16_LE |
| 56 | BOM32_BE = BOM_UTF16_BE |
| 57 | BOM64_LE = BOM_UTF32_LE |
| 58 | BOM64_BE = BOM_UTF32_BE |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 59 | |
| 60 | |
| 61 | ### Codec base classes (defining the API) |
| 62 | |
| 63 | class Codec: |
| 64 | |
| 65 | """ Defines the interface for stateless encoders/decoders. |
| 66 | |
| 67 | The .encode()/.decode() methods may implement different error |
| 68 | handling schemes by providing the errors argument. These |
| 69 | string values are defined: |
| 70 | |
Guido van Rossum | d8855fd | 2000-03-24 22:14:19 +0000 | [diff] [blame] | 71 | 'strict' - raise a ValueError error (or a subclass) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 72 | 'ignore' - ignore the character and continue with the next |
| 73 | 'replace' - replace with a suitable replacement character; |
| 74 | Python will use the official U+FFFD REPLACEMENT |
| 75 | CHARACTER for the builtin Unicode codecs. |
| 76 | |
| 77 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 78 | def encode(self, input, errors='strict'): |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 79 | |
Fred Drake | 3e74c0d | 2000-03-17 15:40:35 +0000 | [diff] [blame] | 80 | """ Encodes the object input and returns a tuple (output |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 81 | object, length consumed). |
| 82 | |
| 83 | errors defines the error handling to apply. It defaults to |
| 84 | 'strict' handling. |
| 85 | |
| 86 | The method may not store state in the Codec instance. Use |
| 87 | StreamCodec for codecs which have to keep state in order to |
| 88 | make encoding/decoding efficient. |
| 89 | |
| 90 | The encoder must be able to handle zero length input and |
| 91 | return an empty object of the output object type in this |
| 92 | situation. |
| 93 | |
| 94 | """ |
| 95 | raise NotImplementedError |
| 96 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 97 | def decode(self, input, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 98 | |
| 99 | """ Decodes the object input and returns a tuple (output |
| 100 | object, length consumed). |
| 101 | |
| 102 | input must be an object which provides the bf_getreadbuf |
| 103 | buffer slot. Python strings, buffer objects and memory |
| 104 | mapped files are examples of objects providing this slot. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 105 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 106 | errors defines the error handling to apply. It defaults to |
| 107 | 'strict' handling. |
| 108 | |
| 109 | The method may not store state in the Codec instance. Use |
| 110 | StreamCodec for codecs which have to keep state in order to |
| 111 | make encoding/decoding efficient. |
| 112 | |
| 113 | The decoder must be able to handle zero length input and |
| 114 | return an empty object of the output object type in this |
| 115 | situation. |
| 116 | |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 117 | """ |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 118 | raise NotImplementedError |
| 119 | |
| 120 | # |
| 121 | # The StreamWriter and StreamReader class provide generic working |
Andrew M. Kuchling | 97c5635 | 2001-09-18 20:29:48 +0000 | [diff] [blame] | 122 | # interfaces which can be used to implement new encoding submodules |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 123 | # very easily. See encodings/utf_8.py for an example on how this is |
| 124 | # done. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 125 | # |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 126 | |
| 127 | class StreamWriter(Codec): |
| 128 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 129 | def __init__(self, stream, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 130 | |
| 131 | """ Creates a StreamWriter instance. |
| 132 | |
| 133 | stream must be a file-like object open for writing |
| 134 | (binary) data. |
| 135 | |
| 136 | The StreamWriter may implement different error handling |
| 137 | schemes by providing the errors keyword argument. These |
| 138 | parameters are defined: |
| 139 | |
| 140 | 'strict' - raise a ValueError (or a subclass) |
| 141 | 'ignore' - ignore the character and continue with the next |
| 142 | 'replace'- replace with a suitable replacement character |
| 143 | |
| 144 | """ |
| 145 | self.stream = stream |
| 146 | self.errors = errors |
| 147 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 148 | def write(self, object): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 149 | |
| 150 | """ Writes the object's contents encoded to self.stream. |
| 151 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 152 | data, consumed = self.encode(object, self.errors) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 153 | self.stream.write(data) |
| 154 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 155 | def writelines(self, list): |
| 156 | |
| 157 | """ Writes the concatenated list of strings to the stream |
| 158 | using .write(). |
| 159 | """ |
| 160 | self.write(''.join(list)) |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 161 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 162 | def reset(self): |
| 163 | |
| 164 | """ Flushes and resets the codec buffers used for keeping state. |
| 165 | |
| 166 | Calling this method should ensure that the data on the |
| 167 | output is put into a clean state, that allows appending |
| 168 | of new fresh data without having to rescan the whole |
| 169 | stream to recover state. |
| 170 | |
| 171 | """ |
| 172 | pass |
| 173 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 174 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 175 | getattr=getattr): |
| 176 | |
| 177 | """ Inherit all other methods from the underlying stream. |
| 178 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 179 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 180 | |
| 181 | ### |
| 182 | |
| 183 | class StreamReader(Codec): |
| 184 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 185 | def __init__(self, stream, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 186 | |
| 187 | """ Creates a StreamReader instance. |
| 188 | |
| 189 | stream must be a file-like object open for reading |
| 190 | (binary) data. |
| 191 | |
| 192 | The StreamReader may implement different error handling |
| 193 | schemes by providing the errors keyword argument. These |
| 194 | parameters are defined: |
| 195 | |
| 196 | 'strict' - raise a ValueError (or a subclass) |
| 197 | 'ignore' - ignore the character and continue with the next |
| 198 | 'replace'- replace with a suitable replacement character; |
| 199 | |
| 200 | """ |
| 201 | self.stream = stream |
| 202 | self.errors = errors |
| 203 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 204 | def read(self, size=-1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 205 | |
| 206 | """ Decodes data from the stream self.stream and returns the |
| 207 | resulting object. |
| 208 | |
| 209 | size indicates the approximate maximum number of bytes to |
| 210 | read from the stream for decoding purposes. The decoder |
| 211 | can modify this setting as appropriate. The default value |
| 212 | -1 indicates to read and decode as much as possible. size |
| 213 | is intended to prevent having to decode huge files in one |
| 214 | step. |
| 215 | |
| 216 | The method should use a greedy read strategy meaning that |
| 217 | it should read as much data as is allowed within the |
| 218 | definition of the encoding and the given size, e.g. if |
| 219 | optional encoding endings or state markers are available |
| 220 | on the stream, these should be read too. |
| 221 | |
| 222 | """ |
| 223 | # Unsliced reading: |
| 224 | if size < 0: |
Andrew M. Kuchling | c6c2838 | 2000-12-10 15:12:14 +0000 | [diff] [blame] | 225 | return self.decode(self.stream.read(), self.errors)[0] |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 226 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 227 | # Sliced reading: |
| 228 | read = self.stream.read |
| 229 | decode = self.decode |
| 230 | data = read(size) |
| 231 | i = 0 |
| 232 | while 1: |
| 233 | try: |
Andrew M. Kuchling | c6c2838 | 2000-12-10 15:12:14 +0000 | [diff] [blame] | 234 | object, decodedbytes = decode(data, self.errors) |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 235 | except ValueError, why: |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 236 | # This method is slow but should work under pretty much |
| 237 | # all conditions; at most 10 tries are made |
| 238 | i = i + 1 |
| 239 | newdata = read(1) |
| 240 | if not newdata or i > 10: |
| 241 | raise |
| 242 | data = data + newdata |
| 243 | else: |
| 244 | return object |
| 245 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 246 | def readline(self, size=None): |
| 247 | |
| 248 | """ Read one line from the input stream and return the |
| 249 | decoded data. |
| 250 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 251 | Note: Unlike the .readlines() method, this method inherits |
| 252 | the line breaking knowledge from the underlying stream's |
| 253 | .readline() method -- there is currently no support for |
| 254 | line breaking using the codec decoder due to lack of line |
| 255 | buffering. Sublcasses should however, if possible, try to |
| 256 | implement this method using their own knowledge of line |
| 257 | breaking. |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 258 | |
| 259 | size, if given, is passed as size argument to the stream's |
| 260 | .readline() method. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 261 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 262 | """ |
| 263 | if size is None: |
| 264 | line = self.stream.readline() |
| 265 | else: |
| 266 | line = self.stream.readline(size) |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 267 | return self.decode(line, self.errors)[0] |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 268 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 269 | |
Martin v. Löwis | b786e61 | 2002-03-05 15:46:38 +0000 | [diff] [blame] | 270 | def readlines(self, sizehint=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 271 | |
| 272 | """ Read all lines available on the input stream |
| 273 | and return them as list of lines. |
| 274 | |
| 275 | Line breaks are implemented using the codec's decoder |
| 276 | method and are included in the list entries. |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 277 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 278 | sizehint, if given, is passed as size argument to the |
| 279 | stream's .read() method. |
| 280 | |
| 281 | """ |
| 282 | if sizehint is None: |
| 283 | data = self.stream.read() |
| 284 | else: |
| 285 | data = self.stream.read(sizehint) |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 286 | return self.decode(data, self.errors)[0].splitlines(1) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 287 | |
| 288 | def reset(self): |
| 289 | |
| 290 | """ Resets the codec buffers used for keeping state. |
| 291 | |
| 292 | Note that no stream repositioning should take place. |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 293 | This method is primarily intended to be able to recover |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 294 | from decoding errors. |
| 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 StreamReaderWriter: |
| 309 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 310 | """ StreamReaderWriter instances allow wrapping streams which |
| 311 | work in both read and write modes. |
| 312 | |
| 313 | The design is such that one can use the factory functions |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 314 | returned by the codec.lookup() function to construct the |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 315 | instance. |
| 316 | |
| 317 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 318 | # Optional attributes set by the file wrappers below |
| 319 | encoding = 'unknown' |
| 320 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 321 | def __init__(self, stream, Reader, Writer, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 322 | |
| 323 | """ Creates a StreamReaderWriter instance. |
| 324 | |
| 325 | stream must be a Stream-like object. |
| 326 | |
| 327 | Reader, Writer must be factory functions or classes |
| 328 | providing the StreamReader, StreamWriter interface resp. |
| 329 | |
| 330 | Error handling is done in the same way as defined for the |
| 331 | StreamWriter/Readers. |
| 332 | |
| 333 | """ |
| 334 | self.stream = stream |
| 335 | self.reader = Reader(stream, errors) |
| 336 | self.writer = Writer(stream, errors) |
| 337 | self.errors = errors |
| 338 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 339 | def read(self, size=-1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 340 | |
| 341 | return self.reader.read(size) |
| 342 | |
Guido van Rossum | d58c26f | 2000-05-01 16:17:32 +0000 | [diff] [blame] | 343 | def readline(self, size=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 344 | |
| 345 | return self.reader.readline(size) |
| 346 | |
Guido van Rossum | d58c26f | 2000-05-01 16:17:32 +0000 | [diff] [blame] | 347 | def readlines(self, sizehint=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 348 | |
| 349 | return self.reader.readlines(sizehint) |
| 350 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 351 | def write(self, data): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 352 | |
| 353 | return self.writer.write(data) |
| 354 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 355 | def writelines(self, list): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 356 | |
| 357 | return self.writer.writelines(list) |
| 358 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 359 | def reset(self): |
| 360 | |
| 361 | self.reader.reset() |
| 362 | self.writer.reset() |
| 363 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 364 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 365 | getattr=getattr): |
| 366 | |
| 367 | """ Inherit all other methods from the underlying stream. |
| 368 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 369 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 370 | |
| 371 | ### |
| 372 | |
| 373 | class StreamRecoder: |
| 374 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 375 | """ StreamRecoder instances provide a frontend - backend |
| 376 | view of encoding data. |
| 377 | |
| 378 | They use the complete set of APIs returned by the |
| 379 | codecs.lookup() function to implement their task. |
| 380 | |
| 381 | Data written to the stream is first decoded into an |
| 382 | intermediate format (which is dependent on the given codec |
| 383 | combination) and then written to the stream using an instance |
| 384 | of the provided Writer class. |
| 385 | |
| 386 | In the other direction, data is read from the stream using a |
| 387 | Reader instance and then return encoded data to the caller. |
| 388 | |
| 389 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 390 | # Optional attributes set by the file wrappers below |
| 391 | data_encoding = 'unknown' |
| 392 | file_encoding = 'unknown' |
| 393 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 394 | def __init__(self, stream, encode, decode, Reader, Writer, |
| 395 | errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 396 | |
| 397 | """ Creates a StreamRecoder instance which implements a two-way |
| 398 | conversion: encode and decode work on the frontend (the |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 399 | input to .read() and output of .write()) while |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 400 | Reader and Writer work on the backend (reading and |
Fred Drake | 908670c | 2000-03-17 15:42:11 +0000 | [diff] [blame] | 401 | writing to the stream). |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 402 | |
| 403 | You can use these objects to do transparent direct |
| 404 | recodings from e.g. latin-1 to utf-8 and back. |
| 405 | |
| 406 | stream must be a file-like object. |
| 407 | |
| 408 | encode, decode must adhere to the Codec interface, Reader, |
| 409 | Writer must be factory functions or classes providing the |
| 410 | StreamReader, StreamWriter interface resp. |
| 411 | |
| 412 | encode and decode are needed for the frontend translation, |
| 413 | Reader and Writer for the backend translation. Unicode is |
| 414 | used as intermediate encoding. |
| 415 | |
| 416 | Error handling is done in the same way as defined for the |
| 417 | StreamWriter/Readers. |
| 418 | |
| 419 | """ |
| 420 | self.stream = stream |
| 421 | self.encode = encode |
| 422 | self.decode = decode |
| 423 | self.reader = Reader(stream, errors) |
| 424 | self.writer = Writer(stream, errors) |
| 425 | self.errors = errors |
| 426 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 427 | def read(self, size=-1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 428 | |
| 429 | data = self.reader.read(size) |
| 430 | data, bytesencoded = self.encode(data, self.errors) |
| 431 | return data |
| 432 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 433 | def readline(self, size=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 434 | |
| 435 | if size is None: |
| 436 | data = self.reader.readline() |
| 437 | else: |
| 438 | data = self.reader.readline(size) |
| 439 | data, bytesencoded = self.encode(data, self.errors) |
| 440 | return data |
| 441 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 442 | def readlines(self, sizehint=None): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 443 | |
| 444 | if sizehint is None: |
| 445 | data = self.reader.read() |
| 446 | else: |
| 447 | data = self.reader.read(sizehint) |
| 448 | data, bytesencoded = self.encode(data, self.errors) |
| 449 | return data.splitlines(1) |
| 450 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 451 | def write(self, data): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 452 | |
| 453 | data, bytesdecoded = self.decode(data, self.errors) |
| 454 | return self.writer.write(data) |
| 455 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 456 | def writelines(self, list): |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 457 | |
| 458 | data = ''.join(list) |
| 459 | data, bytesdecoded = self.decode(data, self.errors) |
| 460 | return self.writer.write(data) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 461 | |
| 462 | def reset(self): |
| 463 | |
| 464 | self.reader.reset() |
| 465 | self.writer.reset() |
| 466 | |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 467 | def __getattr__(self, name, |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 468 | getattr=getattr): |
| 469 | |
| 470 | """ Inherit all other methods from the underlying stream. |
| 471 | """ |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 472 | return getattr(self.stream, name) |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 473 | |
| 474 | ### Shortcuts |
| 475 | |
Marc-André Lemburg | 349a3d3 | 2000-06-21 21:21:04 +0000 | [diff] [blame] | 476 | def open(filename, mode='rb', encoding=None, errors='strict', buffering=1): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 477 | |
| 478 | """ Open an encoded file using the given mode and return |
| 479 | a wrapped version providing transparent encoding/decoding. |
| 480 | |
| 481 | Note: The wrapped version will only accept the object format |
| 482 | defined by the codecs, i.e. Unicode objects for most builtin |
| 483 | codecs. Output is also codec dependent and will usually by |
| 484 | Unicode as well. |
| 485 | |
Marc-André Lemburg | 349a3d3 | 2000-06-21 21:21:04 +0000 | [diff] [blame] | 486 | Files are always opened in binary mode, even if no binary mode |
| 487 | was specified. Thisis done to avoid data loss due to encodings |
| 488 | using 8-bit values. The default file mode is 'rb' meaning to |
| 489 | open the file in binary read mode. |
| 490 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 491 | encoding specifies the encoding which is to be used for the |
| 492 | the file. |
| 493 | |
| 494 | errors may be given to define the error handling. It defaults |
| 495 | to 'strict' which causes ValueErrors to be raised in case an |
| 496 | encoding error occurs. |
| 497 | |
| 498 | buffering has the same meaning as for the builtin open() API. |
| 499 | It defaults to line buffered. |
| 500 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 501 | The returned wrapped file object provides an extra attribute |
| 502 | .encoding which allows querying the used encoding. This |
| 503 | attribute is only available if an encoding was specified as |
| 504 | parameter. |
| 505 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 506 | """ |
| 507 | if encoding is not None and \ |
| 508 | 'b' not in mode: |
| 509 | # Force opening of the file in binary mode |
| 510 | mode = mode + 'b' |
| 511 | file = __builtin__.open(filename, mode, buffering) |
| 512 | if encoding is None: |
| 513 | return file |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 514 | (e, d, sr, sw) = lookup(encoding) |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 515 | srw = StreamReaderWriter(file, sr, sw, errors) |
| 516 | # Add attributes to simplify introspection |
| 517 | srw.encoding = encoding |
| 518 | return srw |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 519 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 520 | def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'): |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 521 | |
| 522 | """ Return a wrapped version of file which provides transparent |
| 523 | encoding translation. |
| 524 | |
| 525 | Strings written to the wrapped file are interpreted according |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 526 | to the given data_encoding and then written to the original |
| 527 | file as string using file_encoding. The intermediate encoding |
| 528 | will usually be Unicode but depends on the specified codecs. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 529 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 530 | Strings are read from the file using file_encoding and then |
| 531 | passed back to the caller as string using data_encoding. |
| 532 | |
| 533 | If file_encoding is not given, it defaults to data_encoding. |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 534 | |
| 535 | errors may be given to define the error handling. It defaults |
| 536 | to 'strict' which causes ValueErrors to be raised in case an |
| 537 | encoding error occurs. |
| 538 | |
Fred Drake | 49fd107 | 2000-04-13 14:11:21 +0000 | [diff] [blame] | 539 | The returned wrapped file object provides two extra attributes |
| 540 | .data_encoding and .file_encoding which reflect the given |
| 541 | parameters of the same name. The attributes can be used for |
| 542 | introspection by Python programs. |
| 543 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 544 | """ |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 545 | if file_encoding is None: |
| 546 | file_encoding = data_encoding |
| 547 | encode, decode = lookup(data_encoding)[:2] |
| 548 | Reader, Writer = lookup(file_encoding)[2:] |
| 549 | sr = StreamRecoder(file, |
Tim Peters | 30324a7 | 2001-05-15 17:19:16 +0000 | [diff] [blame] | 550 | encode, decode, Reader, Writer, |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 551 | errors) |
| 552 | # Add attributes to simplify introspection |
| 553 | sr.data_encoding = data_encoding |
| 554 | sr.file_encoding = file_encoding |
| 555 | return sr |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 556 | |
Marc-André Lemburg | aa32c5a | 2001-09-19 11:24:48 +0000 | [diff] [blame] | 557 | ### Helpers for codec lookup |
| 558 | |
| 559 | def getencoder(encoding): |
| 560 | |
| 561 | """ Lookup up the codec for the given encoding and return |
| 562 | its encoder function. |
| 563 | |
| 564 | Raises a LookupError in case the encoding cannot be found. |
| 565 | |
| 566 | """ |
| 567 | return lookup(encoding)[0] |
| 568 | |
| 569 | def getdecoder(encoding): |
| 570 | |
| 571 | """ Lookup up the codec for the given encoding and return |
| 572 | its decoder function. |
| 573 | |
| 574 | Raises a LookupError in case the encoding cannot be found. |
| 575 | |
| 576 | """ |
| 577 | return lookup(encoding)[1] |
| 578 | |
| 579 | def getreader(encoding): |
| 580 | |
| 581 | """ Lookup up the codec for the given encoding and return |
| 582 | its StreamReader class or factory function. |
| 583 | |
| 584 | Raises a LookupError in case the encoding cannot be found. |
| 585 | |
| 586 | """ |
| 587 | return lookup(encoding)[2] |
| 588 | |
| 589 | def getwriter(encoding): |
| 590 | |
| 591 | """ Lookup up the codec for the given encoding and return |
| 592 | its StreamWriter class or factory function. |
| 593 | |
| 594 | Raises a LookupError in case the encoding cannot be found. |
| 595 | |
| 596 | """ |
| 597 | return lookup(encoding)[3] |
| 598 | |
Marc-André Lemburg | a866df8 | 2001-01-03 21:29:14 +0000 | [diff] [blame] | 599 | ### Helpers for charmap-based codecs |
| 600 | |
| 601 | def make_identity_dict(rng): |
| 602 | |
| 603 | """ make_identity_dict(rng) -> dict |
| 604 | |
| 605 | Return a dictionary where elements of the rng sequence are |
| 606 | mapped to themselves. |
Tim Peters | 88869f9 | 2001-01-14 23:36:06 +0000 | [diff] [blame] | 607 | |
Marc-André Lemburg | a866df8 | 2001-01-03 21:29:14 +0000 | [diff] [blame] | 608 | """ |
| 609 | res = {} |
| 610 | for i in rng: |
| 611 | res[i]=i |
| 612 | return res |
| 613 | |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 614 | def make_encoding_map(decoding_map): |
| 615 | |
| 616 | """ Creates an encoding map from a decoding map. |
| 617 | |
| 618 | If a target mapping in the decoding map occurrs multiple |
| 619 | times, then that target is mapped to None (undefined mapping), |
| 620 | causing an exception when encountered by the charmap codec |
| 621 | during translation. |
| 622 | |
| 623 | One example where this happens is cp875.py which decodes |
| 624 | multiple character to \u001a. |
| 625 | |
| 626 | """ |
| 627 | m = {} |
| 628 | for k,v in decoding_map.items(): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 629 | if not v in m: |
Marc-André Lemburg | 716cf91 | 2001-05-16 09:41:45 +0000 | [diff] [blame] | 630 | m[v] = k |
| 631 | else: |
| 632 | m[v] = None |
| 633 | return m |
Tim Peters | 3a2ab1a | 2001-05-29 06:06:54 +0000 | [diff] [blame] | 634 | |
Martin v. Löwis | 6cd441d | 2001-07-31 08:54:55 +0000 | [diff] [blame] | 635 | # Tell modulefinder that using codecs probably needs the encodings |
| 636 | # package |
| 637 | _false = 0 |
| 638 | if _false: |
| 639 | import encodings |
| 640 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 641 | ### Tests |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 642 | |
Guido van Rossum | 0612d84 | 2000-03-10 23:20:43 +0000 | [diff] [blame] | 643 | if __name__ == '__main__': |
| 644 | |
| 645 | import sys |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 646 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 647 | # Make stdout translate Latin-1 output into UTF-8 output |
| 648 | sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8') |
Guido van Rossum | 1c89b0e | 2000-04-11 15:41:38 +0000 | [diff] [blame] | 649 | |
Guido van Rossum | a327713 | 2000-04-11 15:37:43 +0000 | [diff] [blame] | 650 | # Have stdin translate Latin-1 input into UTF-8 input |
| 651 | sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1') |