codecs.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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 an 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. if chars < 0:
  367. # For compatibility with other read() methods that take a
  368. # single argument
  369. chars = size
  370. # read until we get the required number of characters (if available)
  371. while True:
  372. # can the request be satisfied from the character buffer?
  373. if chars >= 0:
  374. if len(self.charbuffer) >= chars:
  375. break
  376. # we need more data
  377. if size < 0:
  378. newdata = self.stream.read()
  379. else:
  380. newdata = self.stream.read(size)
  381. # decode bytes (those remaining from the last call included)
  382. data = self.bytebuffer + newdata
  383. try:
  384. newchars, decodedbytes = self.decode(data, self.errors)
  385. except UnicodeDecodeError, exc:
  386. if firstline:
  387. newchars, decodedbytes = self.decode(data[:exc.start], self.errors)
  388. lines = newchars.splitlines(True)
  389. if len(lines)<=1:
  390. raise
  391. else:
  392. raise
  393. # keep undecoded bytes until the next call
  394. self.bytebuffer = data[decodedbytes:]
  395. # put new characters in the character buffer
  396. self.charbuffer += newchars
  397. # there was no data available
  398. if not newdata:
  399. break
  400. if chars < 0:
  401. # Return everything we've got
  402. result = self.charbuffer
  403. self.charbuffer = ""
  404. else:
  405. # Return the first chars characters
  406. result = self.charbuffer[:chars]
  407. self.charbuffer = self.charbuffer[chars:]
  408. return result
  409. def readline(self, size=None, keepends=True):
  410. """ Read one line from the input stream and return the
  411. decoded data.
  412. size, if given, is passed as size argument to the
  413. read() method.
  414. """
  415. # If we have lines cached from an earlier read, return
  416. # them unconditionally
  417. if self.linebuffer:
  418. line = self.linebuffer[0]
  419. del self.linebuffer[0]
  420. if len(self.linebuffer) == 1:
  421. # revert to charbuffer mode; we might need more data
  422. # next time
  423. self.charbuffer = self.linebuffer[0]
  424. self.linebuffer = None
  425. if not keepends:
  426. line = line.splitlines(False)[0]
  427. return line
  428. readsize = size or 72
  429. line = ""
  430. # If size is given, we call read() only once
  431. while True:
  432. data = self.read(readsize, firstline=True)
  433. if data:
  434. # If we're at a "\r" read one extra character (which might
  435. # be a "\n") to get a proper line ending. If the stream is
  436. # temporarily exhausted we return the wrong line ending.
  437. if data.endswith("\r"):
  438. data += self.read(size=1, chars=1)
  439. line += data
  440. lines = line.splitlines(True)
  441. if lines:
  442. if len(lines) > 1:
  443. # More than one line result; the first line is a full line
  444. # to return
  445. line = lines[0]
  446. del lines[0]
  447. if len(lines) > 1:
  448. # cache the remaining lines
  449. lines[-1] += self.charbuffer
  450. self.linebuffer = lines
  451. self.charbuffer = None
  452. else:
  453. # only one remaining line, put it back into charbuffer
  454. self.charbuffer = lines[0] + self.charbuffer
  455. if not keepends:
  456. line = line.splitlines(False)[0]
  457. break
  458. line0withend = lines[0]
  459. line0withoutend = lines[0].splitlines(False)[0]
  460. if line0withend != line0withoutend: # We really have a line end
  461. # Put the rest back together and keep it until the next call
  462. self.charbuffer = "".join(lines[1:]) + self.charbuffer
  463. if keepends:
  464. line = line0withend
  465. else:
  466. line = line0withoutend
  467. break
  468. # we didn't get anything or this was our only try
  469. if not data or size is not None:
  470. if line and not keepends:
  471. line = line.splitlines(False)[0]
  472. break
  473. if readsize<8000:
  474. readsize *= 2
  475. return line
  476. def readlines(self, sizehint=None, keepends=True):
  477. """ Read all lines available on the input stream
  478. and return them as list of lines.
  479. Line breaks are implemented using the codec's decoder
  480. method and are included in the list entries.
  481. sizehint, if given, is ignored since there is no efficient
  482. way to finding the true end-of-line.
  483. """
  484. data = self.read()
  485. return data.splitlines(keepends)
  486. def reset(self):
  487. """ Resets the codec buffers used for keeping state.
  488. Note that no stream repositioning should take place.
  489. This method is primarily intended to be able to recover
  490. from decoding errors.
  491. """
  492. self.bytebuffer = ""
  493. self.charbuffer = u""
  494. self.linebuffer = None
  495. def seek(self, offset, whence=0):
  496. """ Set the input stream's current position.
  497. Resets the codec buffers used for keeping state.
  498. """
  499. self.stream.seek(offset, whence)
  500. self.reset()
  501. def next(self):
  502. """ Return the next decoded line from the input stream."""
  503. line = self.readline()
  504. if line:
  505. return line
  506. raise StopIteration
  507. def __iter__(self):
  508. return self
  509. def __getattr__(self, name,
  510. getattr=getattr):
  511. """ Inherit all other methods from the underlying stream.
  512. """
  513. return getattr(self.stream, name)
  514. def __enter__(self):
  515. return self
  516. def __exit__(self, type, value, tb):
  517. self.stream.close()
  518. ###
  519. class StreamReaderWriter:
  520. """ StreamReaderWriter instances allow wrapping streams which
  521. work in both read and write modes.
  522. The design is such that one can use the factory functions
  523. returned by the codec.lookup() function to construct the
  524. instance.
  525. """
  526. # Optional attributes set by the file wrappers below
  527. encoding = 'unknown'
  528. def __init__(self, stream, Reader, Writer, errors='strict'):
  529. """ Creates a StreamReaderWriter instance.
  530. stream must be a Stream-like object.
  531. Reader, Writer must be factory functions or classes
  532. providing the StreamReader, StreamWriter interface resp.
  533. Error handling is done in the same way as defined for the
  534. StreamWriter/Readers.
  535. """
  536. self.stream = stream
  537. self.reader = Reader(stream, errors)
  538. self.writer = Writer(stream, errors)
  539. self.errors = errors
  540. def read(self, size=-1):
  541. return self.reader.read(size)
  542. def readline(self, size=None):
  543. return self.reader.readline(size)
  544. def readlines(self, sizehint=None):
  545. return self.reader.readlines(sizehint)
  546. def next(self):
  547. """ Return the next decoded line from the input stream."""
  548. return self.reader.next()
  549. def __iter__(self):
  550. return self
  551. def write(self, data):
  552. return self.writer.write(data)
  553. def writelines(self, list):
  554. return self.writer.writelines(list)
  555. def reset(self):
  556. self.reader.reset()
  557. self.writer.reset()
  558. def seek(self, offset, whence=0):
  559. self.stream.seek(offset, whence)
  560. self.reader.reset()
  561. if whence == 0 and offset == 0:
  562. self.writer.reset()
  563. def __getattr__(self, name,
  564. getattr=getattr):
  565. """ Inherit all other methods from the underlying stream.
  566. """
  567. return getattr(self.stream, name)
  568. # these are needed to make "with codecs.open(...)" work properly
  569. def __enter__(self):
  570. return self
  571. def __exit__(self, type, value, tb):
  572. self.stream.close()
  573. ###
  574. class StreamRecoder:
  575. """ StreamRecoder instances provide a frontend - backend
  576. view of encoding data.
  577. They use the complete set of APIs returned by the
  578. codecs.lookup() function to implement their task.
  579. Data written to the stream is first decoded into an
  580. intermediate format (which is dependent on the given codec
  581. combination) and then written to the stream using an instance
  582. of the provided Writer class.
  583. In the other direction, data is read from the stream using a
  584. Reader instance and then return encoded data to the caller.
  585. """
  586. # Optional attributes set by the file wrappers below
  587. data_encoding = 'unknown'
  588. file_encoding = 'unknown'
  589. def __init__(self, stream, encode, decode, Reader, Writer,
  590. errors='strict'):
  591. """ Creates a StreamRecoder instance which implements a two-way
  592. conversion: encode and decode work on the frontend (the
  593. input to .read() and output of .write()) while
  594. Reader and Writer work on the backend (reading and
  595. writing to the stream).
  596. You can use these objects to do transparent direct
  597. recodings from e.g. latin-1 to utf-8 and back.
  598. stream must be a file-like object.
  599. encode, decode must adhere to the Codec interface, Reader,
  600. Writer must be factory functions or classes providing the
  601. StreamReader, StreamWriter interface resp.
  602. encode and decode are needed for the frontend translation,
  603. Reader and Writer for the backend translation. Unicode is
  604. used as intermediate encoding.
  605. Error handling is done in the same way as defined for the
  606. StreamWriter/Readers.
  607. """
  608. self.stream = stream
  609. self.encode = encode
  610. self.decode = decode
  611. self.reader = Reader(stream, errors)
  612. self.writer = Writer(stream, errors)
  613. self.errors = errors
  614. def read(self, size=-1):
  615. data = self.reader.read(size)
  616. data, bytesencoded = self.encode(data, self.errors)
  617. return data
  618. def readline(self, size=None):
  619. if size is None:
  620. data = self.reader.readline()
  621. else:
  622. data = self.reader.readline(size)
  623. data, bytesencoded = self.encode(data, self.errors)
  624. return data
  625. def readlines(self, sizehint=None):
  626. data = self.reader.read()
  627. data, bytesencoded = self.encode(data, self.errors)
  628. return data.splitlines(1)
  629. def next(self):
  630. """ Return the next decoded line from the input stream."""
  631. data = self.reader.next()
  632. data, bytesencoded = self.encode(data, self.errors)
  633. return data
  634. def __iter__(self):
  635. return self
  636. def write(self, data):
  637. data, bytesdecoded = self.decode(data, self.errors)
  638. return self.writer.write(data)
  639. def writelines(self, list):
  640. data = ''.join(list)
  641. data, bytesdecoded = self.decode(data, self.errors)
  642. return self.writer.write(data)
  643. def reset(self):
  644. self.reader.reset()
  645. self.writer.reset()
  646. def __getattr__(self, name,
  647. getattr=getattr):
  648. """ Inherit all other methods from the underlying stream.
  649. """
  650. return getattr(self.stream, name)
  651. def __enter__(self):
  652. return self
  653. def __exit__(self, type, value, tb):
  654. self.stream.close()
  655. ### Shortcuts
  656. def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):
  657. """ Open an encoded file using the given mode and return
  658. a wrapped version providing transparent encoding/decoding.
  659. Note: The wrapped version will only accept the object format
  660. defined by the codecs, i.e. Unicode objects for most builtin
  661. codecs. Output is also codec dependent and will usually be
  662. Unicode as well.
  663. Files are always opened in binary mode, even if no binary mode
  664. was specified. This is done to avoid data loss due to encodings
  665. using 8-bit values. The default file mode is 'rb' meaning to
  666. open the file in binary read mode.
  667. encoding specifies the encoding which is to be used for the
  668. file.
  669. errors may be given to define the error handling. It defaults
  670. to 'strict' which causes ValueErrors to be raised in case an
  671. encoding error occurs.
  672. buffering has the same meaning as for the builtin open() API.
  673. It defaults to line buffered.
  674. The returned wrapped file object provides an extra attribute
  675. .encoding which allows querying the used encoding. This
  676. attribute is only available if an encoding was specified as
  677. parameter.
  678. """
  679. if encoding is not None:
  680. if 'U' in mode:
  681. # No automatic conversion of '\n' is done on reading and writing
  682. mode = mode.strip().replace('U', '')
  683. if mode[:1] not in set('rwa'):
  684. mode = 'r' + mode
  685. if 'b' not in mode:
  686. # Force opening of the file in binary mode
  687. mode = mode + 'b'
  688. file = __builtin__.open(filename, mode, buffering)
  689. if encoding is None:
  690. return file
  691. info = lookup(encoding)
  692. srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  693. # Add attributes to simplify introspection
  694. srw.encoding = encoding
  695. return srw
  696. def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
  697. """ Return a wrapped version of file which provides transparent
  698. encoding translation.
  699. Strings written to the wrapped file are interpreted according
  700. to the given data_encoding and then written to the original
  701. file as string using file_encoding. The intermediate encoding
  702. will usually be Unicode but depends on the specified codecs.
  703. Strings are read from the file using file_encoding and then
  704. passed back to the caller as string using data_encoding.
  705. If file_encoding is not given, it defaults to data_encoding.
  706. errors may be given to define the error handling. It defaults
  707. to 'strict' which causes ValueErrors to be raised in case an
  708. encoding error occurs.
  709. The returned wrapped file object provides two extra attributes
  710. .data_encoding and .file_encoding which reflect the given
  711. parameters of the same name. The attributes can be used for
  712. introspection by Python programs.
  713. """
  714. if file_encoding is None:
  715. file_encoding = data_encoding
  716. data_info = lookup(data_encoding)
  717. file_info = lookup(file_encoding)
  718. sr = StreamRecoder(file, data_info.encode, data_info.decode,
  719. file_info.streamreader, file_info.streamwriter, errors)
  720. # Add attributes to simplify introspection
  721. sr.data_encoding = data_encoding
  722. sr.file_encoding = file_encoding
  723. return sr
  724. ### Helpers for codec lookup
  725. def getencoder(encoding):
  726. """ Lookup up the codec for the given encoding and return
  727. its encoder function.
  728. Raises a LookupError in case the encoding cannot be found.
  729. """
  730. return lookup(encoding).encode
  731. def getdecoder(encoding):
  732. """ Lookup up the codec for the given encoding and return
  733. its decoder function.
  734. Raises a LookupError in case the encoding cannot be found.
  735. """
  736. return lookup(encoding).decode
  737. def getincrementalencoder(encoding):
  738. """ Lookup up the codec for the given encoding and return
  739. its IncrementalEncoder class or factory function.
  740. Raises a LookupError in case the encoding cannot be found
  741. or the codecs doesn't provide an incremental encoder.
  742. """
  743. encoder = lookup(encoding).incrementalencoder
  744. if encoder is None:
  745. raise LookupError(encoding)
  746. return encoder
  747. def getincrementaldecoder(encoding):
  748. """ Lookup up the codec for the given encoding and return
  749. its IncrementalDecoder class or factory function.
  750. Raises a LookupError in case the encoding cannot be found
  751. or the codecs doesn't provide an incremental decoder.
  752. """
  753. decoder = lookup(encoding).incrementaldecoder
  754. if decoder is None:
  755. raise LookupError(encoding)
  756. return decoder
  757. def getreader(encoding):
  758. """ Lookup up the codec for the given encoding and return
  759. its StreamReader class or factory function.
  760. Raises a LookupError in case the encoding cannot be found.
  761. """
  762. return lookup(encoding).streamreader
  763. def getwriter(encoding):
  764. """ Lookup up the codec for the given encoding and return
  765. its StreamWriter class or factory function.
  766. Raises a LookupError in case the encoding cannot be found.
  767. """
  768. return lookup(encoding).streamwriter
  769. def iterencode(iterator, encoding, errors='strict', **kwargs):
  770. """
  771. Encoding iterator.
  772. Encodes the input strings from the iterator using an IncrementalEncoder.
  773. errors and kwargs are passed through to the IncrementalEncoder
  774. constructor.
  775. """
  776. encoder = getincrementalencoder(encoding)(errors, **kwargs)
  777. for input in iterator:
  778. output = encoder.encode(input)
  779. if output:
  780. yield output
  781. output = encoder.encode("", True)
  782. if output:
  783. yield output
  784. def iterdecode(iterator, encoding, errors='strict', **kwargs):
  785. """
  786. Decoding iterator.
  787. Decodes the input strings from the iterator using an IncrementalDecoder.
  788. errors and kwargs are passed through to the IncrementalDecoder
  789. constructor.
  790. """
  791. decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  792. for input in iterator:
  793. output = decoder.decode(input)
  794. if output:
  795. yield output
  796. output = decoder.decode("", True)
  797. if output:
  798. yield output
  799. ### Helpers for charmap-based codecs
  800. def make_identity_dict(rng):
  801. """ make_identity_dict(rng) -> dict
  802. Return a dictionary where elements of the rng sequence are
  803. mapped to themselves.
  804. """
  805. res = {}
  806. for i in rng:
  807. res[i]=i
  808. return res
  809. def make_encoding_map(decoding_map):
  810. """ Creates an encoding map from a decoding map.
  811. If a target mapping in the decoding map occurs multiple
  812. times, then that target is mapped to None (undefined mapping),
  813. causing an exception when encountered by the charmap codec
  814. during translation.
  815. One example where this happens is cp875.py which decodes
  816. multiple character to \\u001a.
  817. """
  818. m = {}
  819. for k,v in decoding_map.items():
  820. if not v in m:
  821. m[v] = k
  822. else:
  823. m[v] = None
  824. return m
  825. ### error handlers
  826. try:
  827. strict_errors = lookup_error("strict")
  828. ignore_errors = lookup_error("ignore")
  829. replace_errors = lookup_error("replace")
  830. xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")
  831. backslashreplace_errors = lookup_error("backslashreplace")
  832. except LookupError:
  833. # In --disable-unicode builds, these error handler are missing
  834. strict_errors = None
  835. ignore_errors = None
  836. replace_errors = None
  837. xmlcharrefreplace_errors = None
  838. backslashreplace_errors = None
  839. # Tell modulefinder that using codecs probably needs the encodings
  840. # package
  841. _false = 0
  842. if _false:
  843. import encodings
  844. ### Tests
  845. if __name__ == '__main__':
  846. # Make stdout translate Latin-1 output into UTF-8 output
  847. sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  848. # Have stdin translate Latin-1 input into UTF-8 input
  849. sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')