0

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 console, 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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Seems helpful. I can try it with ctypes, but does WaitForMultipleObjects work with ordinary console? It will help a lot to have working example in a different language before trying to do the same with ctypes.
@techtonik: This example looks like it might help. And here's one from Microsoft.
Thanks. Even though there are problems with clearing the buffer, at least WaitForMultipleObjects seems to work.
0

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.

1 Comment

That's the most obvious suggestion, but I don't want to miss CPU cycles if a need in heavy background processing arises.
0

msvcrt.getch()

3 Comments

That's still a blocking function.
well yeah. You either use a blocking function, or you poll using up CPU.
Plenty of other options in native Win32, it just remains to be seen whether python lets you get there from here. Yes, to some degree all event-driven programming requires some blocking function, the trick is to use a blocking function that processes all types of events, not dedicated to a single one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.