codecs.py 36 KB

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