7 if sys.platform != "win32" or done:
11 original_stderr = sys.stderr
13 # If any exception occurs in this code, we'll probably try to print it on stderr,
14 # which makes for frustrating debugging if stderr is directed to our wrapper.
15 # So be paranoid about catching errors and reporting them to original_stderr,
16 # so that we can at least see them.
17 def _complain(message):
18 print >>original_stderr, isinstance(message, str) and message or repr(message)
19 log.msg(message, level=log.WEIRD)
22 from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
23 from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID
24 from allmydata.util import log
25 from allmydata.util.encodingutil import canonical_encoding
27 # Work around <http://bugs.python.org/issue6058>.
28 codecs.register(lambda name: name == 'cp65001' and codecs.lookup('utf-8') or None)
30 # Make Unicode console output work independently of the current code page.
31 # This also fixes <http://bugs.python.org/issue1602>.
32 # Credit to Michael Kaplan <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx>
34 # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
36 # <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
37 # HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
38 # returns INVALID_HANDLE_VALUE, NULL, or a valid handle
40 # <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
41 # DWORD WINAPI GetFileType(DWORD hFile);
43 # <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
44 # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);
46 GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
47 STD_OUTPUT_HANDLE = DWORD(-11)
48 STD_ERROR_HANDLE = DWORD(-12)
49 GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32))
50 FILE_TYPE_CHAR = 0x0002
51 FILE_TYPE_REMOTE = 0x8000
52 GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32))
53 INVALID_HANDLE_VALUE = DWORD(-1).value
55 def not_a_console(handle):
56 if handle == INVALID_HANDLE_VALUE or handle is None:
58 return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
59 or GetConsoleMode(handle, byref(DWORD())) == 0)
61 old_stdout_fileno = None
62 old_stderr_fileno = None
63 if hasattr(sys.stdout, 'fileno'):
64 old_stdout_fileno = sys.stdout.fileno()
65 if hasattr(sys.stderr, 'fileno'):
66 old_stderr_fileno = sys.stderr.fileno()
70 real_stdout = (old_stdout_fileno == STDOUT_FILENO)
71 real_stderr = (old_stderr_fileno == STDERR_FILENO)
74 hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
75 if not_a_console(hStdout):
79 hStderr = GetStdHandle(STD_ERROR_HANDLE)
80 if not_a_console(hStderr):
83 if real_stdout or real_stderr:
84 # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars,
85 # LPDWORD lpCharsWritten, LPVOID lpReserved);
87 WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID) \
88 (("WriteConsoleW", windll.kernel32))
91 def __init__(self, hConsole, stream, fileno, name):
92 self._hConsole = hConsole
96 self.softspace = False
98 self.encoding = 'utf-8'
100 if hasattr(stream, 'encoding') and canonical_encoding(stream.encoding) != 'utf-8':
101 log.msg("%s: %r had encoding %r, but we're going to write UTF-8 to it" %
102 (name, stream, stream.encoding), level=log.CURIOUS)
108 # don't really close the handle, that would only cause problems
113 if self._hConsole is None:
117 _complain("%s.flush: %r from %r" % (self.name, e, self._stream))
120 def write(self, text):
122 if self._hConsole is None:
123 if isinstance(text, unicode):
124 text = text.encode('utf-8')
125 self._stream.write(text)
127 if not isinstance(text, unicode):
128 text = str(text).decode('utf-8')
129 remaining = len(text)
132 retval = WriteConsoleW(self._hConsole, text, remaining, byref(n), None)
133 if retval == 0 or n.value == 0:
134 raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value))
136 if remaining == 0: break
137 text = text[n.value:]
139 _complain("%s.write: %r" % (self.name, e))
142 def writelines(self, lines):
147 _complain("%s.writelines: %r" % (self.name, e))
151 sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '<Unicode console stdout>')
153 sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '<Unicode redirected stdout>')
156 sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '<Unicode console stderr>')
158 sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '<Unicode redirected stderr>')
160 _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,))
162 # Unmangle command-line arguments.
163 GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
164 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int)) \
165 (("CommandLineToArgvW", windll.shell32))
168 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
171 return re.sub(ur'\x7f[0-9a-fA-F]*\;', lambda m: unichr(int(m.group(0)[1:-1], 16)), s)
174 sys.argv = [unmangle(argv_unicode[i]).encode('utf-8') for i in xrange(1, argc.value)]
176 _complain("%s: could not unmangle Unicode arguments.\n%r"
177 % (sys.argv[0], [argv_unicode[i] for i in xrange(1, argc.value)]))
180 if sys.argv[0].endswith('.pyscript'):
181 sys.argv[0] = sys.argv[0][:-9]