|
| 1 | +from __future__ import unicode_literals |
| 2 | + |
| 3 | +from ctypes import POINTER |
| 4 | +from ctypes import windll |
| 5 | +from ctypes import WinError |
| 6 | +from ctypes import WINFUNCTYPE |
| 7 | +from ctypes.wintypes import BOOL |
| 8 | +from ctypes.wintypes import DWORD |
| 9 | +from ctypes.wintypes import HANDLE |
| 10 | + |
| 11 | +STD_OUTPUT_HANDLE = -11 |
| 12 | +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 |
| 13 | + |
| 14 | + |
| 15 | +def bool_errcheck(result, func, args): |
| 16 | + if not result: |
| 17 | + raise WinError() |
| 18 | + return args |
| 19 | + |
| 20 | + |
| 21 | +GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)( |
| 22 | + ("GetStdHandle", windll.kernel32), |
| 23 | + ((1, "nStdHandle"), ) |
| 24 | +) |
| 25 | + |
| 26 | +GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))( |
| 27 | + ("GetConsoleMode", windll.kernel32), |
| 28 | + ((1, "hConsoleHandle"), (2, "lpMode")) |
| 29 | +) |
| 30 | +GetConsoleMode.errcheck = bool_errcheck |
| 31 | + |
| 32 | +SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)( |
| 33 | + ("SetConsoleMode", windll.kernel32), |
| 34 | + ((1, "hConsoleHandle"), (1, "dwMode")) |
| 35 | +) |
| 36 | +SetConsoleMode.errcheck = bool_errcheck |
| 37 | + |
| 38 | + |
| 39 | +def enable_virtual_terminal_processing(): |
| 40 | + """As of Windows 10, the Windows console supports (some) ANSI escape |
| 41 | + sequences, but it needs to be enabled using `SetConsoleMode` first. |
| 42 | +
|
| 43 | + More info on the escape sequences supported: |
| 44 | + https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx |
| 45 | +
|
| 46 | + """ |
| 47 | + stdout = GetStdHandle(STD_OUTPUT_HANDLE) |
| 48 | + flags = GetConsoleMode(stdout) |
| 49 | + SetConsoleMode(stdout, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
0 commit comments