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?