Skip to content

Instantly share code, notes, and snippets.

@jhasse
Created June 12, 2017 18:09
Show Gist options
  • Save jhasse/4566a83b40a08d7b4987444276e4dddc to your computer and use it in GitHub Desktop.
Save jhasse/4566a83b40a08d7b4987444276e4dddc to your computer and use it in GitHub Desktop.
try:
import msvcrt
import atexit
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# input flags
ENABLE_PROCESSED_INPUT = 0x0001
ENABLE_LINE_INPUT = 0x0002
ENABLE_ECHO_INPUT = 0x0004
ENABLE_WINDOW_INPUT = 0x0008
ENABLE_MOUSE_INPUT = 0x0010
ENABLE_INSERT_MODE = 0x0020
ENABLE_QUICK_EDIT_MODE = 0x0040
# output flags
ENABLE_PROCESSED_OUTPUT = 0x0001
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 # VT100 (Win 10)
def check_zero(result, func, args):
if not result:
err = ctypes.get_last_error()
if err:
raise ctypes.WinError(err)
return args
if not hasattr(wintypes, 'LPDWORD'): # PY2
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
kernel32.GetConsoleMode.errcheck= check_zero
kernel32.GetConsoleMode.argtypes = (
wintypes.HANDLE, # _In_ hConsoleHandle
wintypes.LPDWORD,) # _Out_ lpMode
kernel32.SetConsoleMode.errcheck= check_zero
kernel32.SetConsoleMode.argtypes = (
wintypes.HANDLE, # _In_ hConsoleHandle
wintypes.DWORD,) # _Out_ lpMode
def set_console_mode(mode, output=True):
'''Set the mode of the active console input or output
buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
'''
device = r'\\.\CONOUT$' if output else r'\\.\CONIN$'
with open(device, 'r+') as con:
hCon = msvcrt.get_osfhandle(con.fileno())
kernel32.SetConsoleMode(hCon, mode)
def get_console_mode(output=True):
'''Get the mode of the active console input or output
buffer. Note that if the process isn't attached to a
console, this function raises an EBADF IOError.
'''
device = r'\\.\CONOUT$' if output else r'\\.\CONIN$'
with open(device, 'r+') as con:
mode = wintypes.DWORD()
hCon = msvcrt.get_osfhandle(con.fileno())
kernel32.GetConsoleMode(hCon, ctypes.byref(mode))
return mode.value
set_console_mode(get_console_mode() | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment