[Python-ideas] Suggestion: Clear screen command for the REPL

eryk sun eryksun at gmail.com
Sat Sep 17 09:34:41 EDT 2016


On Sat, Sep 17, 2016 at 11:11 AM, João Matos <jcrmatos at gmail.com> wrote:
>On 17-09-2016 12:07, Oleg Broytman wrote:
>>
>>     Pressing [Ctrl]+[L] works for me.
>
> Doesn't work on Windows.

Windows 10 added VT100 support to the console, so you can create a
little cls() function to clear the screen:

    cls = lambda: print('\x1b[1J', end='', flush=True)

VT100 support isn't enabled by default. However, cmd.exe always
enables this mode. So run doskey.exe via os.system to enable VT100
mode while setting a convenient "cls" alias:

    import os
    os.system(r'doskey /exename=python.exe cls=cls()')

This alias substitutes "cls()" for "cls" at the beginning of a line.
This saves you from having to type "()" all the time. The alias isn't
active for other programs; e.g. if you execute
subprocess.call('powershell'), then "cls" will be the PowerShell alias
for Clear-Host.

You can also use ctypes instead of os.system and doskey.exe:

    import ctypes
    kernel32 = ctypes.WinDLL('kernel32')
    hStdOut = kernel32.GetStdHandle(-11)

    # enable VT100 mode
    mode = (ctypes.c_uint * 1)()
    kernel32.GetConsoleMode(hStdOut, mode)
    kernel32.SetConsoleMode(hStdOut, mode[0] | 4)

    # define a cls() function and set a console alias
    cls = lambda: print('\x1b[1J', end='', flush=True)
    kernel32.AddConsoleAliasW('cls', 'cls()', 'python.exe')

For older versions of Windows you can use ANSICON or ConEmu, which use
DLL injection to extend the console API. Python's colorama and
pyreadline modules should also work for this.


More information about the Python-ideas mailing list