7 if sys.platform != "win32" or done:
12 from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
13 from ctypes.wintypes import BOOL, HANDLE, DWORD, UINT, LPWSTR, LPCWSTR, LPVOID
14 from allmydata.util import log
15 from allmydata.util.encodingutil import canonical_encoding
17 # <https://msdn.microsoft.com/en-us/library/ms680621%28VS.85%29.aspx>
18 SetErrorMode = WINFUNCTYPE(UINT, UINT)(("SetErrorMode", windll.kernel32))
19 SEM_FAILCRITICALERRORS = 0x0001
20 SEM_NOOPENFILEERRORBOX = 0x8000
22 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX)
24 original_stderr = sys.stderr
26 # If any exception occurs in this code, we'll probably try to print it on stderr,
27 # which makes for frustrating debugging if stderr is directed to our wrapper.
28 # So be paranoid about catching errors and reporting them to original_stderr,
29 # so that we can at least see them.
30 def _complain(message):
31 print >>original_stderr, isinstance(message, str) and message or repr(message)
32 log.msg(message, level=log.WEIRD)
34 # Work around <http://bugs.python.org/issue6058>.
35 codecs.register(lambda name: name == 'cp65001' and codecs.lookup('utf-8') or None)
37 # Make Unicode console output work independently of the current code page.
38 # This also fixes <http://bugs.python.org/issue1602>.
39 # Credit to Michael Kaplan <https://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx>
41 # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
43 # <https://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
44 # HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
45 # returns INVALID_HANDLE_VALUE, NULL, or a valid handle
47 # <https://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
48 # DWORD WINAPI GetFileType(DWORD hFile);
50 # <https://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
51 # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);
53 GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
54 STD_OUTPUT_HANDLE = DWORD(-11)
55 STD_ERROR_HANDLE = DWORD(-12)
56 GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32))
57 FILE_TYPE_CHAR = 0x0002
58 FILE_TYPE_REMOTE = 0x8000
59 GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32))
60 INVALID_HANDLE_VALUE = DWORD(-1).value
62 def not_a_console(handle):
63 if handle == INVALID_HANDLE_VALUE or handle is None:
65 return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
66 or GetConsoleMode(handle, byref(DWORD())) == 0)
68 old_stdout_fileno = None
69 old_stderr_fileno = None
70 if hasattr(sys.stdout, 'fileno'):
71 old_stdout_fileno = sys.stdout.fileno()
72 if hasattr(sys.stderr, 'fileno'):
73 old_stderr_fileno = sys.stderr.fileno()
77 real_stdout = (old_stdout_fileno == STDOUT_FILENO)
78 real_stderr = (old_stderr_fileno == STDERR_FILENO)
81 hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
82 if not_a_console(hStdout):
86 hStderr = GetStdHandle(STD_ERROR_HANDLE)
87 if not_a_console(hStderr):
90 if real_stdout or real_stderr:
91 # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars,
92 # LPDWORD lpCharsWritten, LPVOID lpReserved);
94 WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID) \
95 (("WriteConsoleW", windll.kernel32))
98 def __init__(self, hConsole, stream, fileno, name):
99 self._hConsole = hConsole
100 self._stream = stream
101 self._fileno = fileno
103 self.softspace = False
105 self.encoding = 'utf-8'
107 if hasattr(stream, 'encoding') and canonical_encoding(stream.encoding) != 'utf-8':
108 log.msg("%s: %r had encoding %r, but we're going to write UTF-8 to it" %
109 (name, stream, stream.encoding), level=log.CURIOUS)
115 # don't really close the handle, that would only cause problems
120 if self._hConsole is None:
124 _complain("%s.flush: %r from %r" % (self.name, e, self._stream))
127 def write(self, text):
129 if self._hConsole is None:
130 if isinstance(text, unicode):
131 text = text.encode('utf-8')
132 self._stream.write(text)
134 if not isinstance(text, unicode):
135 text = str(text).decode('utf-8')
136 remaining = len(text)
139 # There is a shorter-than-documented limitation on the length of the string
140 # passed to WriteConsoleW (see #1232).
141 retval = WriteConsoleW(self._hConsole, text, min(remaining, 10000), byref(n), None)
142 if retval == 0 or n.value == 0:
143 raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value))
145 if remaining == 0: break
146 text = text[n.value:]
148 _complain("%s.write: %r" % (self.name, e))
151 def writelines(self, lines):
156 _complain("%s.writelines: %r" % (self.name, e))
160 sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '<Unicode console stdout>')
162 sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '<Unicode redirected stdout>')
165 sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '<Unicode console stderr>')
167 sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '<Unicode redirected stderr>')
169 _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,))
171 # This works around <http://bugs.python.org/issue2128>.
172 GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
173 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int)) \
174 (("CommandLineToArgvW", windll.shell32))
177 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
179 # Because of <http://bugs.python.org/issue8775> (and similar limitations in
180 # twisted), the 'bin/tahoe' script cannot invoke us with the actual Unicode arguments.
181 # Instead it "mangles" or escapes them using \x7F as an escape character, which we
184 return re.sub(ur'\x7F[0-9a-fA-F]*\;', lambda m: unichr(int(m.group(0)[1:-1], 16)), s)
187 argv = [unmangle(argv_unicode[i]).encode('utf-8') for i in xrange(0, argc.value)]
189 _complain("%s: could not unmangle Unicode arguments.\n%r"
190 % (sys.argv[0], [argv_unicode[i] for i in xrange(0, argc.value)]))
193 # Take only the suffix with the same number of arguments as sys.argv.
194 # This accounts for anything that can cause initial arguments to be stripped,
195 # for example, the Python interpreter or any options passed to it, or runner
196 # scripts such as 'coverage run'. It works even if there are no such arguments,
197 # as in the case of a frozen executable created by bb-freeze or similar.
199 sys.argv = argv[-len(sys.argv):]
200 if sys.argv[0].endswith('.pyscript'):
201 sys.argv[0] = sys.argv[0][:-9]