Monitor key presses in Python?

Dave Angel davea at davea.name
Mon Sep 9 14:19:40 EDT 2013


On 9/9/2013 13:39, 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?

What is usually meant by "a callback" is a function object.  In Python,
functions are first class objects.  You just use the function name
without the parentheses.

def my_function():
    print "Executing my_function"

b = my_function   # b is now a function object

b() 

Likewise, instead of storing it in a global, you might pass it to a
method which stores it as an object attribute, or whatever.

Also of interest is that you can easily create partial functions, where
some of the parameters are already decided.  See the docs for
functools.partial

And if you're trying to use a method as a callback, you can store the
bound-method, which is effectively a partial including the self
parameter.

Finally, don't forget lambda functions, which can be useful if you're
trying to create a simple function and don't need a name for it.


-- 
DaveA





More information about the Python-list mailing list