Polling the keyboard (detect a keypress) in python

K. Brafford picture K. Brafford · Nov 15, 2008 · Viewed 131.3k times · Source

How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):

   while 1:
      # doing amazing pythonic embedded stuff
      # ...

      # periodically do a non-blocking check to see if
      # we are being told to do something else
      x = keyboard.read(1000, timeout = 0)

      if len(x):
          # ok, some key got pressed
          # do something

What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.

Answer

S.Lott picture S.Lott · Nov 15, 2008

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.