How to ask the user to enter a string with a timeout built into python on a windows machine?

wants to ask the user to enter something, but does not want to wait forever. There is a solution for Linux, Inputting a keyboard with a timeout in Python , but I'm in a Windows environment. can anyone help me?

+3
source share
1 answer

Credit Alex Martelli

Unfortunately, on Windows, select.select only works on sockets, not ordinary files and the console. So, if you want to work on Windows, you need a different approach. On Windows only, the Python standard library is a small module called msvcrt, including functions such as msvcrt.kbhit that tells you that any keystroke is waiting to be read. Here you can sys.stdout.write a request, then enter a small loop (including time.sleep (0.2) or so) that waits to find out if the user has pressed the key - if so, you can sys.stdin.readline and etc., but if after your desired timeout does not work was hit, then just return an empty string from your function.

, -, ( - !). , , ( , sys.stdin, . msvcrt.getch, ). , , - , , , , .

+2

Source: https://habr.com/ru/post/1739329/