1

I am using the following code (from here How to put text in input line: how to ask for user input on the command line while providing a 'default' answer that the user can edit or delete?) to prompt the user to modify a default string (on Windows):

import win32console

_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

def input_def(prompt, default=''):
    keys = []
    for c in str(default):
        evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
        evt.Char = c
        evt.RepeatCount = 1
        evt.KeyDown = True
        keys.append(evt)

    _stdin.WriteConsoleInput(keys)
    return input(prompt)

if __name__ == '__main__':
    name = input_def('Folder name: ', 'it works!!!')
    print()
    print(name)

My problem is that sometimes, one or multiple characters are added to my default string, most of the time at the beginning. That is to say, the above code would display Folder name: Ait works!!! for instance in the console.

My keys variable seems to have the correct length so I guess there is something wrong with _stdin. Is it when _stdin is initialized to _stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)? How can I get rid of these random characters?

Sulli
  • 763
  • 1
  • 11
  • 33

1 Answers1

1

Call _stdin.FlushConsoleInputBuffer() before _stdin.WriteConsoleInput(keys). You could make this a default true option to flush the input buffer. Override it to false if you need to keep the existing contents.

Ideally your script should support a fallback if stdin is a disk file or pipe (e.g. an MSYS terminal) instead of a console, or at least fail gracefully in this case.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111