[Tutor] how does one poll the keyboard?

dman dsh8290@rit.edu
Fri, 23 Nov 2001 12:00:19 -0500


On Fri, Nov 23, 2001 at 11:37:09AM -0500, tonycervone wrote:
| How does one poll the keyboard with Python to see if a specific key(
| that I choose to define as the key to press) has been pressed while a
| program is running?  I guess the script would poll the keyboard and
| run in the background of a main program.Of course, the script could
| not have an indefinite loop so as to prevent the program from running.
| The program will then quickly run the script and if the key has been
| pressed a message will appear that such a key has been pressed.

Is this the sort of thing you are looking for?

(untested, but should give the idea)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import sys
import threading

# this is to signal when the key_pressed flag has useful data,
# it will be "set" to indicate that the key_pressed flag has been set
# accordingly
data_ready = threading.Event()

class KeyboardPoller( threading.Thread ) :
    def run( self ) :
        global key_pressed
        ch = sys.stdin.read( 1 ) 
        if ch == 'K' : # the key you are interested in
            key_pressed = 1
        else :
            key_pressed = 0
        data_ready.set()

def main() :
    poller = KeyboardPoller()
    poller.start()

    # check the flag in a manner that is not blocking
    while not data_ready.isSet() :
        print "doing something (main loop)"

    if key_pressed :
        print "You pressed the magic key!"
    print "all done now"

if __name__ == "__main__" :
    main()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



What this does is create a thread that reads in a single character of
input (it could read more if you want it to).  When that character is
read (the input blocks until data is ready) it is compared against
some constant and the 'key_pressed' flag is set to true if it matches.
Then the threading.Event instance's flag is set to true to indicate
that it is safe for the main thread to read the value of the
key_pressed variable.  If the main thread tries to read the value
prior to that, the semantics are undefined (it might not exist, it
might exist but have only part of its value, etc).


It is likely simpler for your script to simply request input at the
right time and just wait for the input to exist.  You are aware that
input is buffered, right?  You can type stuff into the console at any
time and the program will read it in, in order, when it wants to.

HTH,
-D