On 10/16/20, Barry Scott <ba...@barrys-emacs.org> wrote:
>
> I find that you have to do this to turn on ANSI processing in CMD.EXE on
> Window 10 and I assume earlier Windwows as wel:

You mean the console-session host (conhost.exe). This has nothing to
do with the CMD shell. People often confuse CLI shells (CMD,
PowerShell, bash) with the console/terminal that they use for standard
I/O.

Virtual Terminal mode is supported by the new console in Windows 10 --
not in earlier versions of Windows and not with the legacy console in
Windows 10. If you need to support ANSI sequences with the legacy
console host, consider using a third-party library such as colorama.

You can enable VT mode by default for regular console sessions (i.e.
not headless sessions such as under Windows Terminal, for which it's
always enabled) by setting a DWORD value of 1 named
"VirtualTerminalLevel" in the registry key "HKCU\Console".

> import ctypes
> kernel32 = ctypes.windll.kernel32
> # turn on the console ANSI colour handling
> kernel32.SetConsoleMode( kernel32.GetStdHandle( -11 ), 7 )

You should enable the flag in the current mode value and implement
error handling:

    import ctypes
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

    STD_OUTPUT_HANDLE = -11
    ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
    INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value

    kernel32.GetStdHandle.restype = ctypes.c_void_p

    hstdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    if hstdout == INVALID_HANDLE_VALUE:
        raise ctypes.WinError(ctypes.get_last_error())

    mode = ctypes.c_ulong()
    if not kernel32.GetConsoleMode(hstdout, ctypes.byref(mode)):
        raise ctypes.WinError(ctypes.get_last_error())

    mode.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
    if not kernel32.SetConsoleMode(hstdout, mode):
        raise ctypes.WinError(ctypes.get_last_error())
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/UHIZNALCL7UGX5LXJACHHKOHMUMXACKN/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to