PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/codecs.py

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