Polling the keyboard (detect a keypress) in python Polling the keyboard (detect a keypress) in python python python

Polling the keyboard (detect a keypress) in python


The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.


A solution using the curses module. Printing a numeric value corresponding to each key pressed:

import cursesdef main(stdscr):    # do not wait for input when calling getch    stdscr.nodelay(1)    while True:        # get keyboard input, returns -1 if none available        c = stdscr.getch()        if c != -1:            # print numeric value            stdscr.addstr(str(c) + ' ')            stdscr.refresh()            # return curser to start position            stdscr.move(0, 0)if __name__ == '__main__':    curses.wrapper(main)


Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:

import msvcrt def kbfunc():    x = msvcrt.kbhit()   if x:       ret = ord(msvcrt.getch())    else:       ret = 0    return ret