Monitor key presses in Python?

Michael Torrie torriem at gmail.com
Mon Sep 9 22:43:34 EDT 2013


On 09/09/2013 11:39 AM, eamonnrea at gmail.com wrote:
> Is there a way to detect if the user presses a key in Python that
> works on most OS's? I've only seen 1 method, and that only works in
> Python 2.6 and less.  If you get the key, can you store it in a
> variable?
> 
> Also, is there a way to create a callback in Python?

Some python programs display a graphical user interface.  Others run in
a text-mode console (dos prompt, unix shell, etc).  And yet others don't
have any display at all.  If you're talking about a graphical user
interface app (windows, dialogs, buttons, etc), then you'll have to rely
on the particular user interface library you are using to provide that
sort of access.  If you're just running in a dos box, or a unix
terminal, then there are other ways of doing what you want, but I'm not
sure any one way is portable across all operating systems.  I did find
this code segment that claims to work on windows and unix:

http://code.activestate.com/recipes/134892/

Anyway tell us more about what environment and kind of program you are
dealing with.

As for callbacks, of course.  functions are objects in python.  You can
pass them as arguments, assign them to variables, and then call them.
All graphical user interface libraries rely on them to handle events.



More information about the Python-list mailing list