fix_encoding.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Collection of functions and classes to fix various encoding problems on
  5. multiple platforms with python.
  6. """
  7. from __future__ import print_function
  8. import codecs
  9. import locale
  10. import os
  11. import sys
  12. # Prevents initializing multiple times.
  13. _SYS_ARGV_PROCESSED = False
  14. def complain(message):
  15. """If any exception occurs in this file, we'll probably try to print it
  16. on stderr, which makes for frustrating debugging if stderr is directed
  17. to our wrapper. So be paranoid about catching errors and reporting them
  18. to sys.__stderr__, so that the user has a higher chance to see them.
  19. """
  20. print(
  21. isinstance(message, str) and message or repr(message),
  22. file=sys.__stderr__)
  23. def fix_default_encoding():
  24. """Forces utf8 solidly on all platforms.
  25. By default python execution environment is lazy and defaults to ascii
  26. encoding.
  27. http://uucode.com/blog/2007/03/23/shut-up-you-dummy-7-bit-python/
  28. """
  29. if sys.getdefaultencoding() == 'utf-8':
  30. return False
  31. # Regenerate setdefaultencoding.
  32. reload(sys)
  33. # Module 'sys' has no 'setdefaultencoding' member
  34. # pylint: disable=no-member
  35. sys.setdefaultencoding('utf-8')
  36. for attr in dir(locale):
  37. if attr[0:3] != 'LC_':
  38. continue
  39. aref = getattr(locale, attr)
  40. try:
  41. locale.setlocale(aref, '')
  42. except locale.Error:
  43. continue
  44. try:
  45. lang, _ = locale.getdefaultlocale()
  46. except (TypeError, ValueError):
  47. continue
  48. if lang:
  49. try:
  50. locale.setlocale(aref, (lang, 'UTF-8'))
  51. except locale.Error:
  52. os.environ[attr] = lang + '.UTF-8'
  53. try:
  54. locale.setlocale(locale.LC_ALL, '')
  55. except locale.Error:
  56. pass
  57. return True
  58. ###############################
  59. # Windows specific
  60. def fix_win_sys_argv(encoding):
  61. """Converts sys.argv to 'encoding' encoded string.
  62. utf-8 is recommended.
  63. Works around <http://bugs.python.org/issue2128>.
  64. """
  65. global _SYS_ARGV_PROCESSED
  66. if _SYS_ARGV_PROCESSED:
  67. return False
  68. if sys.version_info.major == 3:
  69. _SYS_ARGV_PROCESSED = True
  70. return True
  71. # These types are available on linux but not Mac.
  72. # pylint: disable=no-name-in-module,F0401
  73. from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE
  74. from ctypes.wintypes import LPCWSTR, LPWSTR
  75. # <http://msdn.microsoft.com/en-us/library/ms683156.aspx>
  76. GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32))
  77. # <http://msdn.microsoft.com/en-us/library/bb776391.aspx>
  78. CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
  79. ('CommandLineToArgvW', windll.shell32))
  80. argc = c_int(0)
  81. argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
  82. argv = [
  83. argv_unicode[i].encode(encoding, 'replace') for i in range(0, argc.value)
  84. ]
  85. if not hasattr(sys, 'frozen'):
  86. # If this is an executable produced by py2exe or bbfreeze, then it
  87. # will have been invoked directly. Otherwise, unicode_argv[0] is the
  88. # Python interpreter, so skip that.
  89. argv = argv[1:]
  90. # Also skip option arguments to the Python interpreter.
  91. while len(argv) > 0:
  92. arg = argv[0]
  93. if not arg.startswith(b'-') or arg == b'-':
  94. break
  95. argv = argv[1:]
  96. if arg == u'-m':
  97. # sys.argv[0] should really be the absolute path of the
  98. # module source, but never mind.
  99. break
  100. if arg == u'-c':
  101. argv[0] = u'-c'
  102. break
  103. sys.argv = argv
  104. _SYS_ARGV_PROCESSED = True
  105. return True
  106. def fix_win_codec():
  107. """Works around <http://bugs.python.org/issue6058>."""
  108. # <http://msdn.microsoft.com/en-us/library/dd317756.aspx>
  109. try:
  110. codecs.lookup('cp65001')
  111. return False
  112. except LookupError:
  113. codecs.register(
  114. lambda name: name == 'cp65001' and codecs.lookup('utf-8') or None)
  115. return True
  116. class WinUnicodeOutputBase(object):
  117. """Base class to adapt sys.stdout or sys.stderr to behave correctly on
  118. Windows.
  119. Setting encoding to utf-8 is recommended.
  120. """
  121. def __init__(self, fileno, name, encoding):
  122. # Corresponding file handle.
  123. self._fileno = fileno
  124. self.encoding = encoding
  125. self.name = name
  126. self.closed = False
  127. self.softspace = False
  128. self.mode = 'w'
  129. @staticmethod
  130. def isatty():
  131. return False
  132. def close(self):
  133. # Don't really close the handle, that would only cause problems.
  134. self.closed = True
  135. def fileno(self):
  136. return self._fileno
  137. def flush(self):
  138. raise NotImplementedError()
  139. def write(self, text):
  140. raise NotImplementedError()
  141. def writelines(self, lines):
  142. try:
  143. for line in lines:
  144. self.write(line)
  145. except Exception as e:
  146. complain('%s.writelines: %r' % (self.name, e))
  147. raise
  148. class WinUnicodeConsoleOutput(WinUnicodeOutputBase):
  149. """Output adapter to a Windows Console.
  150. Understands how to use the win32 console API.
  151. """
  152. def __init__(self, console_handle, fileno, stream_name, encoding):
  153. super(WinUnicodeConsoleOutput, self).__init__(
  154. fileno, '<Unicode console %s>' % stream_name, encoding)
  155. # Handle to use for WriteConsoleW
  156. self._console_handle = console_handle
  157. # Loads the necessary function.
  158. # These types are available on linux but not Mac.
  159. # pylint: disable=no-name-in-module,F0401
  160. from ctypes import byref, GetLastError, POINTER, windll, WINFUNCTYPE
  161. from ctypes.wintypes import BOOL, DWORD, HANDLE, LPWSTR
  162. from ctypes.wintypes import LPVOID # pylint: disable=no-name-in-module
  163. self._DWORD = DWORD
  164. self._byref = byref
  165. # <http://msdn.microsoft.com/en-us/library/ms687401.aspx>
  166. self._WriteConsoleW = WINFUNCTYPE(
  167. BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(
  168. ('WriteConsoleW', windll.kernel32))
  169. self._GetLastError = GetLastError
  170. def flush(self):
  171. # No need to flush the console since it's immediate.
  172. pass
  173. def write(self, text):
  174. try:
  175. if sys.version_info.major == 2 and not isinstance(text, unicode):
  176. # Convert to unicode.
  177. text = str(text).decode(self.encoding, 'replace')
  178. elif sys.version_info.major == 3 and isinstance(text, bytes):
  179. # Bytestrings need to be decoded to a string before being passed to
  180. # Windows.
  181. text = text.decode(self.encoding, 'replace')
  182. remaining = len(text)
  183. while remaining > 0:
  184. n = self._DWORD(0)
  185. # There is a shorter-than-documented limitation on the length of the
  186. # string passed to WriteConsoleW. See
  187. # <http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232>.
  188. retval = self._WriteConsoleW(
  189. self._console_handle, text,
  190. min(remaining, 10000),
  191. self._byref(n), None)
  192. if retval == 0 or n.value == 0:
  193. raise IOError(
  194. 'WriteConsoleW returned %r, n.value = %r, last error = %r' % (
  195. retval, n.value, self._GetLastError()))
  196. remaining -= n.value
  197. if not remaining:
  198. break
  199. text = text[int(n.value):]
  200. except Exception as e:
  201. complain('%s.write: %r' % (self.name, e))
  202. raise
  203. class WinUnicodeOutput(WinUnicodeOutputBase):
  204. """Output adaptor to a file output on Windows.
  205. If the standard FileWrite function is used, it will be encoded in the current
  206. code page. WriteConsoleW() permits writing any character.
  207. """
  208. def __init__(self, stream, fileno, encoding):
  209. super(WinUnicodeOutput, self).__init__(
  210. fileno, '<Unicode redirected %s>' % stream.name, encoding)
  211. # Output stream
  212. self._stream = stream
  213. # Flush right now.
  214. self.flush()
  215. def flush(self):
  216. try:
  217. self._stream.flush()
  218. except Exception as e:
  219. complain('%s.flush: %r from %r' % (self.name, e, self._stream))
  220. raise
  221. def write(self, text):
  222. try:
  223. if sys.version_info.major == 2 and isinstance(text, unicode):
  224. # Replace characters that cannot be printed instead of failing.
  225. text = text.encode(self.encoding, 'replace')
  226. if sys.version_info.major == 3 and isinstance(text, bytes):
  227. # Replace characters that cannot be printed instead of failing.
  228. text = text.decode(self.encoding, 'replace')
  229. self._stream.write(text)
  230. except Exception as e:
  231. complain('%s.write: %r' % (self.name, e))
  232. raise
  233. def win_handle_is_a_console(handle):
  234. """Returns True if a Windows file handle is a handle to a console."""
  235. # These types are available on linux but not Mac.
  236. # pylint: disable=no-name-in-module,F0401
  237. from ctypes import byref, POINTER, windll, WINFUNCTYPE
  238. from ctypes.wintypes import BOOL, DWORD, HANDLE
  239. FILE_TYPE_CHAR = 0x0002
  240. FILE_TYPE_REMOTE = 0x8000
  241. INVALID_HANDLE_VALUE = DWORD(-1).value
  242. # <http://msdn.microsoft.com/en-us/library/ms683167.aspx>
  243. GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
  244. ('GetConsoleMode', windll.kernel32))
  245. # <http://msdn.microsoft.com/en-us/library/aa364960.aspx>
  246. GetFileType = WINFUNCTYPE(DWORD, DWORD)(('GetFileType', windll.kernel32))
  247. # GetStdHandle returns INVALID_HANDLE_VALUE, NULL, or a valid handle.
  248. if handle == INVALID_HANDLE_VALUE or handle is None:
  249. return False
  250. return (
  251. (GetFileType(handle) & ~FILE_TYPE_REMOTE) == FILE_TYPE_CHAR and
  252. GetConsoleMode(handle, byref(DWORD())))
  253. def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
  254. """Returns a unicode-compatible stream.
  255. This function will return a direct-Console writing object only if:
  256. - the file number is the expected console file number
  257. - the handle the expected file handle
  258. - the 'real' handle is in fact a handle to a console.
  259. """
  260. old_fileno = getattr(stream, 'fileno', lambda: None)()
  261. if old_fileno == excepted_fileno:
  262. # These types are available on linux but not Mac.
  263. # pylint: disable=no-name-in-module,F0401
  264. from ctypes import windll, WINFUNCTYPE
  265. from ctypes.wintypes import DWORD, HANDLE
  266. # <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
  267. GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))
  268. real_output_handle = GetStdHandle(DWORD(output_handle))
  269. if win_handle_is_a_console(real_output_handle):
  270. # It's a console.
  271. return WinUnicodeConsoleOutput(
  272. real_output_handle, old_fileno, stream.name, encoding)
  273. # It's something else. Create an auto-encoding stream.
  274. return WinUnicodeOutput(stream, old_fileno, encoding)
  275. def fix_win_console(encoding):
  276. """Makes Unicode console output work independently of the current code page.
  277. This also fixes <http://bugs.python.org/issue1602>.
  278. Credit to Michael Kaplan
  279. <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx> and
  280. TZOmegaTZIOY
  281. <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
  282. """
  283. if (isinstance(sys.stdout, WinUnicodeOutputBase) or
  284. isinstance(sys.stderr, WinUnicodeOutputBase)):
  285. return False
  286. try:
  287. # SetConsoleCP and SetConsoleOutputCP could be used to change the code page
  288. # but it's not really useful since the code here is using WriteConsoleW().
  289. # Also, changing the code page is 'permanent' to the console and needs to be
  290. # reverted manually.
  291. # In practice one needs to set the console font to a TTF font to be able to
  292. # see all the characters but it failed for me in practice. In any case, it
  293. # won't throw any exception when printing, which is the important part.
  294. # -11 and -12 are defined in stdio.h
  295. sys.stdout = win_get_unicode_stream(sys.stdout, 1, -11, encoding)
  296. sys.stderr = win_get_unicode_stream(sys.stderr, 2, -12, encoding)
  297. # TODO(maruel): Do sys.stdin with ReadConsoleW(). Albeit the limitation is
  298. # "It doesn't appear to be possible to read Unicode characters in UTF-8
  299. # mode" and this appears to be a limitation of cmd.exe.
  300. except Exception as e:
  301. complain('exception %r while fixing up sys.stdout and sys.stderr' % e)
  302. return True
  303. def fix_encoding():
  304. """Fixes various encoding problems on all platforms.
  305. Should be called at the very beginning of the process.
  306. """
  307. ret = True
  308. if sys.platform == 'win32':
  309. ret &= fix_win_codec()
  310. ret &= fix_default_encoding()
  311. if sys.platform == 'win32':
  312. encoding = sys.getdefaultencoding()
  313. ret &= fix_win_sys_argv(encoding)
  314. ret &= fix_win_console(encoding)
  315. return ret