52
52
os.unsetenv(REINVOKE)
56
55
if sys.platform == 'win32' and sys.stdout.isatty():
57
from ctypes import windll, create_string_buffer, Structure, c_short, c_ushort, byref
56
from ctypes import windll, Structure, c_short, c_ushort, byref
60
class WindowsConsoleWriter():
59
class COORD(Structure):
65
class SMALL_RECT(Structure):
73
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
76
("dwCursorPosition", COORD),
77
("wAttributes", c_ushort),
78
("srWindow", SMALL_RECT),
79
("dwMaximumWindowSize", COORD)
82
STD_OUTPUT_HANDLE = -11
84
def consolereplace_errors(exception):
85
if not isinstance(exception, UnicodeDecodeError):
86
raise TypeError("consolereplace() cannot handle %r" % exception)
87
l = [u"\\%x" % ord(exception.object[pos]) for pos in xrange(exception.start, exception.end)]
88
return (u"\ufffe%s\ufeff" % u"".join(l), exception.end)
90
codecs.register_error("consolereplace", consolereplace_errors)
94
class WindowsConsoleWriter:
61
95
def __init__(self, errors='strict'):
62
96
self.errors = errors
63
97
self.encoding = 'utf_16'
64
self.handle = windll.kernel32.GetStdHandle(-11)
66
class COORD(Structure):
72
class SMALL_RECT(Structure):
80
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
83
("dwCursorPosition", COORD),
84
("wAttributes", c_ushort),
85
("srWindow", SMALL_RECT),
86
("dwMaximumWindowSize", COORD)
98
self.handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
89
100
csbi = CONSOLE_SCREEN_BUFFER_INFO()
90
101
windll.kernel32.GetConsoleScreenBufferInfo(self.handle, byref(csbi))
95
106
self.write(text + "\n")
97
108
def _write(self, text):
98
windll.kernel32.WriteConsoleW(self.handle
99
, text, len(text), 0, 0)
109
windll.kernel32.WriteConsoleW(self.handle, text, len(text), 0, 0)
101
111
def _color(self, color):
102
112
windll.kernel32.SetConsoleTextAttribute(self.handle, color)
104
114
def write(self, text):
105
def consolereplace_errors(exception):
106
if not isinstance(exception, UnicodeDecodeError):
107
raise TypeError("consolereplace() cannot handle %r" % exception)
108
l = [u"\ufffe\\%x\ufeff" % ord(exception.object[pos]) for pos in xrange(exception.start, exception.end)]
109
return (u"%s" % u"".join(l), exception.end)
111
codecs.register_error("consolereplace", consolereplace_errors)
113
115
text = unicode(text, 'utf_8', errors='consolereplace')
115
for x in text.split(u"\ufffe"):
120
b = x.split(u"\ufeff")
124
self._color(self.defattr)
120
self._write(text[i:j])
122
self._color(FOREGROUND_RED)
124
self._write(text[i:j])
126
self._color(self.defattr)
128
self._write(text[i:j])
129
130
def isatty(self): return True