Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

codecs.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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 struct,types,__builtin__
  6. ### Registry and builtin stateless codec functions
  7. try:
  8. from _codecs import *
  9. except ImportError,why:
  10. raise SystemError,\
  11. '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. ### Constants
  15. #
  16. # Byte Order Mark (BOM) and its possible values (BOM_BE, BOM_LE)
  17. #
  18. BOM = struct.pack('=H',0xFEFF)
  19. #
  20. BOM_BE = BOM32_BE = '\376\377'
  21. # corresponds to Unicode U+FEFF in UTF-16 on big endian
  22. # platforms == ZERO WIDTH NO-BREAK SPACE
  23. BOM_LE = BOM32_LE = '\377\376'
  24. # corresponds to Unicode U+FFFE in UTF-16 on little endian
  25. # platforms == defined as being an illegal Unicode character
  26. #
  27. # 64-bit Byte Order Marks
  28. #
  29. BOM64_BE = '\000\000\376\377'
  30. # corresponds to Unicode U+0000FEFF in UCS-4
  31. BOM64_LE = '\377\376\000\000'
  32. # corresponds to Unicode U+0000FFFE in UCS-4
  33. ### Codec base classes (defining the API)
  34. class Codec:
  35. """ Defines the interface for stateless encoders/decoders.
  36. The .encode()/.decode() methods may implement different error
  37. handling schemes by providing the errors argument. These
  38. string values are defined:
  39. 'strict' - raise a ValueError error (or a subclass)
  40. 'ignore' - ignore the character and continue with the next
  41. 'replace' - replace with a suitable replacement character;
  42. Python will use the official U+FFFD REPLACEMENT
  43. CHARACTER for the builtin Unicode codecs.
  44. """
  45. def encode(self,input,errors='strict'):
  46. """ Encodes the object input and returns a tuple (output
  47. object, length consumed).
  48. errors defines the error handling to apply. It defaults to
  49. 'strict' handling.
  50. The method may not store state in the Codec instance. Use
  51. StreamCodec for codecs which have to keep state in order to
  52. make encoding/decoding efficient.
  53. The encoder must be able to handle zero length input and
  54. return an empty object of the output object type in this
  55. situation.
  56. """
  57. raise NotImplementedError
  58. def decode(self,input,errors='strict'):
  59. """ Decodes the object input and returns a tuple (output
  60. object, length consumed).
  61. input must be an object which provides the bf_getreadbuf
  62. buffer slot. Python strings, buffer objects and memory
  63. mapped files are examples of objects providing this slot.
  64. errors defines the error handling to apply. It defaults to
  65. 'strict' handling.
  66. The method may not store state in the Codec instance. Use
  67. StreamCodec for codecs which have to keep state in order to
  68. make encoding/decoding efficient.
  69. The decoder must be able to handle zero length input and
  70. return an empty object of the output object type in this
  71. situation.
  72. """
  73. raise NotImplementedError
  74. #
  75. # The StreamWriter and StreamReader class provide generic working
  76. # interfaces which can be used to implement new encodings submodules
  77. # very easily. See encodings/utf_8.py for an example on how this is
  78. # done.
  79. #
  80. class StreamWriter(Codec):
  81. def __init__(self,stream,errors='strict'):
  82. """ Creates a StreamWriter instance.
  83. stream must be a file-like object open for writing
  84. (binary) data.
  85. The StreamWriter may implement different error handling
  86. schemes by providing the errors keyword argument. These
  87. parameters are defined:
  88. 'strict' - raise a ValueError (or a subclass)
  89. 'ignore' - ignore the character and continue with the next
  90. 'replace'- replace with a suitable replacement character
  91. """
  92. self.stream = stream
  93. self.errors = errors
  94. def write(self, object):
  95. """ Writes the object's contents encoded to self.stream.
  96. """
  97. data, consumed = self.encode(object,self.errors)
  98. self.stream.write(data)
  99. def writelines(self, list):
  100. """ Writes the concatenated list of strings to the stream
  101. using .write().
  102. """
  103. self.write(''.join(list))
  104. def reset(self):
  105. """ Flushes and resets the codec buffers used for keeping state.
  106. Calling this method should ensure that the data on the
  107. output is put into a clean state, that allows appending
  108. of new fresh data without having to rescan the whole
  109. stream to recover state.
  110. """
  111. pass
  112. def __getattr__(self,name,
  113. getattr=getattr):
  114. """ Inherit all other methods from the underlying stream.
  115. """
  116. return getattr(self.stream,name)
  117. ###
  118. class StreamReader(Codec):
  119. def __init__(self,stream,errors='strict'):
  120. """ Creates a StreamReader instance.
  121. stream must be a file-like object open for reading
  122. (binary) data.
  123. The StreamReader may implement different error handling
  124. schemes by providing the errors keyword argument. These
  125. parameters are defined:
  126. 'strict' - raise a ValueError (or a subclass)
  127. 'ignore' - ignore the character and continue with the next
  128. 'replace'- replace with a suitable replacement character;
  129. """
  130. self.stream = stream
  131. self.errors = errors
  132. def read(self, size=-1):
  133. """ Decodes data from the stream self.stream and returns the
  134. resulting object.
  135. size indicates the approximate maximum number of bytes to
  136. read from the stream for decoding purposes. The decoder
  137. can modify this setting as appropriate. The default value
  138. -1 indicates to read and decode as much as possible. size
  139. is intended to prevent having to decode huge files in one
  140. step.
  141. The method should use a greedy read strategy meaning that
  142. it should read as much data as is allowed within the
  143. definition of the encoding and the given size, e.g. if
  144. optional encoding endings or state markers are available
  145. on the stream, these should be read too.
  146. """
  147. # Unsliced reading:
  148. if size < 0:
  149. return self.decode(self.stream.read(), self.errors)[0]
  150. # Sliced reading:
  151. read = self.stream.read
  152. decode = self.decode
  153. data = read(size)
  154. i = 0
  155. while 1:
  156. try:
  157. object, decodedbytes = decode(data, self.errors)
  158. except ValueError,why:
  159. # This method is slow but should work under pretty much
  160. # all conditions; at most 10 tries are made
  161. i = i + 1
  162. newdata = read(1)
  163. if not newdata or i > 10:
  164. raise
  165. data = data + newdata
  166. else:
  167. return object
  168. def readline(self, size=None):
  169. """ Read one line from the input stream and return the
  170. decoded data.
  171. Note: Unlike the .readlines() method, this method inherits
  172. the line breaking knowledge from the underlying stream's
  173. .readline() method -- there is currently no support for
  174. line breaking using the codec decoder due to lack of line
  175. buffering. Sublcasses should however, if possible, try to
  176. implement this method using their own knowledge of line
  177. breaking.
  178. size, if given, is passed as size argument to the stream's
  179. .readline() method.
  180. """
  181. if size is None:
  182. line = self.stream.readline()
  183. else:
  184. line = self.stream.readline(size)
  185. return self.decode(line,self.errors)[0]
  186. def readlines(self, sizehint=0):
  187. """ Read all lines available on the input stream
  188. and return them as list of lines.
  189. Line breaks are implemented using the codec's decoder
  190. method and are included in the list entries.
  191. sizehint, if given, is passed as size argument to the
  192. stream's .read() method.
  193. """
  194. if sizehint is None:
  195. data = self.stream.read()
  196. else:
  197. data = self.stream.read(sizehint)
  198. return self.decode(data,self.errors)[0].splitlines(1)
  199. def reset(self):
  200. """ Resets the codec buffers used for keeping state.
  201. Note that no stream repositioning should take place.
  202. This method is primarily intended to be able to recover
  203. from decoding errors.
  204. """
  205. pass
  206. def __getattr__(self,name,
  207. getattr=getattr):
  208. """ Inherit all other methods from the underlying stream.
  209. """
  210. return getattr(self.stream,name)
  211. ###
  212. class StreamReaderWriter:
  213. """ StreamReaderWriter instances allow wrapping streams which
  214. work in both read and write modes.
  215. The design is such that one can use the factory functions
  216. returned by the codec.lookup() function to construct the
  217. instance.
  218. """
  219. # Optional attributes set by the file wrappers below
  220. encoding = 'unknown'
  221. def __init__(self,stream,Reader,Writer,errors='strict'):
  222. """ Creates a StreamReaderWriter instance.
  223. stream must be a Stream-like object.
  224. Reader, Writer must be factory functions or classes
  225. providing the StreamReader, StreamWriter interface resp.
  226. Error handling is done in the same way as defined for the
  227. StreamWriter/Readers.
  228. """
  229. self.stream = stream
  230. self.reader = Reader(stream, errors)
  231. self.writer = Writer(stream, errors)
  232. self.errors = errors
  233. def read(self,size=-1):
  234. return self.reader.read(size)
  235. def readline(self, size=None):
  236. return self.reader.readline(size)
  237. def readlines(self, sizehint=None):
  238. return self.reader.readlines(sizehint)
  239. def write(self,data):
  240. return self.writer.write(data)
  241. def writelines(self,list):
  242. return self.writer.writelines(list)
  243. def reset(self):
  244. self.reader.reset()
  245. self.writer.reset()
  246. def __getattr__(self,name,
  247. getattr=getattr):
  248. """ Inherit all other methods from the underlying stream.
  249. """
  250. return getattr(self.stream,name)
  251. ###
  252. class StreamRecoder:
  253. """ StreamRecoder instances provide a frontend - backend
  254. view of encoding data.
  255. They use the complete set of APIs returned by the
  256. codecs.lookup() function to implement their task.
  257. Data written to the stream is first decoded into an
  258. intermediate format (which is dependent on the given codec
  259. combination) and then written to the stream using an instance
  260. of the provided Writer class.
  261. In the other direction, data is read from the stream using a
  262. Reader instance and then return encoded data to the caller.
  263. """
  264. # Optional attributes set by the file wrappers below
  265. data_encoding = 'unknown'
  266. file_encoding = 'unknown'
  267. def __init__(self,stream,encode,decode,Reader,Writer,errors='strict'):
  268. """ Creates a StreamRecoder instance which implements a two-way
  269. conversion: encode and decode work on the frontend (the
  270. input to .read() and output of .write()) while
  271. Reader and Writer work on the backend (reading and
  272. writing to the stream).
  273. You can use these objects to do transparent direct
  274. recodings from e.g. latin-1 to utf-8 and back.
  275. stream must be a file-like object.
  276. encode, decode must adhere to the Codec interface, Reader,
  277. Writer must be factory functions or classes providing the
  278. StreamReader, StreamWriter interface resp.
  279. encode and decode are needed for the frontend translation,
  280. Reader and Writer for the backend translation. Unicode is
  281. used as intermediate encoding.
  282. Error handling is done in the same way as defined for the
  283. StreamWriter/Readers.
  284. """
  285. self.stream = stream
  286. self.encode = encode
  287. self.decode = decode
  288. self.reader = Reader(stream, errors)
  289. self.writer = Writer(stream, errors)
  290. self.errors = errors
  291. def read(self,size=-1):
  292. data = self.reader.read(size)
  293. data, bytesencoded = self.encode(data, self.errors)
  294. return data
  295. def readline(self,size=None):
  296. if size is None:
  297. data = self.reader.readline()
  298. else:
  299. data = self.reader.readline(size)
  300. data, bytesencoded = self.encode(data, self.errors)
  301. return data
  302. def readlines(self,sizehint=None):
  303. if sizehint is None:
  304. data = self.reader.read()
  305. else:
  306. data = self.reader.read(sizehint)
  307. data, bytesencoded = self.encode(data, self.errors)
  308. return data.splitlines(1)
  309. def write(self,data):
  310. data, bytesdecoded = self.decode(data, self.errors)
  311. return self.writer.write(data)
  312. def writelines(self,list):
  313. data = ''.join(list)
  314. data, bytesdecoded = self.decode(data, self.errors)
  315. return self.writer.write(data)
  316. def reset(self):
  317. self.reader.reset()
  318. self.writer.reset()
  319. def __getattr__(self,name,
  320. getattr=getattr):
  321. """ Inherit all other methods from the underlying stream.
  322. """
  323. return getattr(self.stream,name)
  324. ### Shortcuts
  325. def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):
  326. """ Open an encoded file using the given mode and return
  327. a wrapped version providing transparent encoding/decoding.
  328. Note: The wrapped version will only accept the object format
  329. defined by the codecs, i.e. Unicode objects for most builtin
  330. codecs. Output is also codec dependent and will usually by
  331. Unicode as well.
  332. Files are always opened in binary mode, even if no binary mode
  333. was specified. Thisis done to avoid data loss due to encodings
  334. using 8-bit values. The default file mode is 'rb' meaning to
  335. open the file in binary read mode.
  336. encoding specifies the encoding which is to be used for the
  337. the file.
  338. errors may be given to define the error handling. It defaults
  339. to 'strict' which causes ValueErrors to be raised in case an
  340. encoding error occurs.
  341. buffering has the same meaning as for the builtin open() API.
  342. It defaults to line buffered.
  343. The returned wrapped file object provides an extra attribute
  344. .encoding which allows querying the used encoding. This
  345. attribute is only available if an encoding was specified as
  346. parameter.
  347. """
  348. if encoding is not None and \
  349. 'b' not in mode:
  350. # Force opening of the file in binary mode
  351. mode = mode + 'b'
  352. file = __builtin__.open(filename, mode, buffering)
  353. if encoding is None:
  354. return file
  355. (e,d,sr,sw) = lookup(encoding)
  356. srw = StreamReaderWriter(file, sr, sw, errors)
  357. # Add attributes to simplify introspection
  358. srw.encoding = encoding
  359. return srw
  360. def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
  361. """ Return a wrapped version of file which provides transparent
  362. encoding translation.
  363. Strings written to the wrapped file are interpreted according
  364. to the given data_encoding and then written to the original
  365. file as string using file_encoding. The intermediate encoding
  366. will usually be Unicode but depends on the specified codecs.
  367. Strings are read from the file using file_encoding and then
  368. passed back to the caller as string using data_encoding.
  369. If file_encoding is not given, it defaults to data_encoding.
  370. errors may be given to define the error handling. It defaults
  371. to 'strict' which causes ValueErrors to be raised in case an
  372. encoding error occurs.
  373. The returned wrapped file object provides two extra attributes
  374. .data_encoding and .file_encoding which reflect the given
  375. parameters of the same name. The attributes can be used for
  376. introspection by Python programs.
  377. """
  378. if file_encoding is None:
  379. file_encoding = data_encoding
  380. encode, decode = lookup(data_encoding)[:2]
  381. Reader, Writer = lookup(file_encoding)[2:]
  382. sr = StreamRecoder(file,
  383. encode,decode,Reader,Writer,
  384. errors)
  385. # Add attributes to simplify introspection
  386. sr.data_encoding = data_encoding
  387. sr.file_encoding = file_encoding
  388. return sr
  389. ### Helpers for charmap-based codecs
  390. def make_identity_dict(rng):
  391. """ make_identity_dict(rng) -> dict
  392. Return a dictionary where elements of the rng sequence are
  393. mapped to themselves.
  394. """
  395. res = {}
  396. for i in rng:
  397. res[i]=i
  398. return res
  399. ### Tests
  400. if __name__ == '__main__':
  401. import sys
  402. # Make stdout translate Latin-1 output into UTF-8 output
  403. sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  404. # Have stdin translate Latin-1 input into UTF-8 input
  405. sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')