input vs. readline

eryk sun eryksun at gmail.com
Fri Jul 8 21:00:46 EDT 2016


On Fri, Jul 8, 2016 at 11:17 PM, John Nagle <nagle at animats.com> wrote:
> If "readline" is imported, "input" gets "readline" capabilities.
> It also loses the ability to import control characters.  It doesn't
> matter where "readline" is imported; an import in some library
> module can trigger this.  You can try this with a simple test
> case:
>
>    print(repr(input()))
>
> as a .py file, run in a console.  Try typing "aaaESCbbb".
> On Windows 7, output is "bbb".  On Linux, it's "aaa\x1bbbb".

The readline module isn't automatically imported for a script, and it
isn't even distributed with Windows Python. You have to install
pyreadline to get readline support on Windows.

You're seeing the readline-like behavior of a Windows console
processed read, i.e. with the console mode ENABLE_PROCESSED_INPUT [1].
The supported command-line editing and history functions are
documented for doskey.exe [2], though in modern Windows systems (based
on NT), it's actually the console (conhost.exe) that implements all of
the doskey functionality. For example, ESC "[c]lears the command from
the display".

Unfortunately processed input is all or nothing; the console doesn't
even process the enter key if processed input is disabled. You'd have
to do a lot of lowish-level ctypes or PyWin32 scripting to get
something usable, but maybe the CRT's getwche() function is good
enough. Try the following:

    #! /usr/bin/python3

    import sys

    if sys.platform == 'win32':
        import msvcrt

        def input(prompt=''):
            if prompt:
                print(prompt, end='', flush=True)
            s = []
            while True:
                c = msvcrt.getwche()
                if c == '\r':
                    break
                s.append(c)
            s = ''.join(s)
            print(prompt, s, sep='')
            return s

    if __name__ == '__main__':
        print(repr(input('test: ')))


[1]: https://msdn.microsoft.com/en-us/library/ms683167
[2]: https://technet.microsoft.com/en-us/library/cc753867



More information about the Python-list mailing list