Asynchronous input notification from Windows console
I need to get user input from console asynchronously, i.e. without blocking. I could use the following Python code to check if there is an input available, but it gives 100% CPU load.
import msvcrt
while not msvcrt.kbhit():
pass
Is there any other way to do this? Is it possible to register a callback function for keyboard events in con开发者_如何学运维sole, for example?
UPDATE: I've created a working solution in Python / ctypes. See example at http://techtonik.rainforce.org/2011/03/asynchronous-input-from-windows-console.html
Using the Win32 API, you would normally call WaitForMultipleObjects
along with your other events to find out which occurred first, the standard input handle itself will be considered triggered whenever any input is available.
A process can specify a console input buffer handle in one of the wait functions to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.
So I would suggest that you look and see whether python has some wrapper for this ability.
There isn't a way to asynchronously get console input/output.
You could try your code with a sleep to prevent the CPU usage spike.
msvcrt.getch()
精彩评论