Reading keyboard input with Python

There are a number of ways to read keyboard input with python. One easy option is to use the curses library, using the getch() method, as shown below:

import curses

cur = curses.initscr() # initialisation

try:
     while True:
        char = cur.getch()
        if char > 0:
            print("Input: " + chr(char) + "\r")
except KeyboardInterrupt:
    print("interrupted...")

curses.endwin() # cleanup
print("Goodbye :-)")

The program above initialises the curses library, then sits in an infinite loop, printing a message whenever any keyboard buttons are pressed. Use ctrl-c to interrupt the loop and clean up curses before exiting gracefully. Note that if you don’t run curses.endwin(), your terminal may exhibit some weird behaviour once the program finishes.

Leave a Reply

Your email address will not be published.