Monitor key presses in Python?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 9 19:37:33 EDT 2013


On Mon, 09 Sep 2013 10:39:43 -0700, eamonnrea 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.

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

I have just tried the above under Linux in Python 3.3, and it works fine. 
I have no way of testing it under Windows.


> If you get the key, can you store it in a variable?

You're new to programming, aren't you? :-)

Yes you can store it in a variable. Anything that is returned can be 
stored in a variable. Here is an example:


py> def example():
...     print("Press any character key... ")
...     c = getch()
...     print("You typed: '%c'" % c)
...
py> example()
Press any character key...
You typed: 'y'


The above is running under Python 3.3.


> Also, is there a way to create a callback in Python?

The answer to your question as you ask it is "Yes, naturally." Callback 
is short for *callback function* and describes the *purpose* of the 
function, not how you write it or what it does. 

But a better answer is, "A callback to what? It depends on what is doing 
the calling back."


-- 
Steven



More information about the Python-list mailing list