fix_encoding.py 12 KB

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