How do I get a single keypress at a time?
For Windows, see:
how-do-i-check-for-a-keypress-without-blocking
For Unix variants: There are several solutions. It’s straightforward to do this using curses, but curses is a fairly large module to learn. Here’s a solution without curses:
import termios, fcntl, sys, os, select fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = oldterm[:]: r, w, e = select.select([fd], [], []) if r: c = sys.stdin.read(1) print "Got character", repr(c) if c == "q": break # quit, until the user presses ‘q’ to quit.
termios.tcsetattr() turns off stdin’s echoing and disables canonical mode. fcntl.fnctl() is used to obtain stdin’s file descriptor flags and modify them for non-blocking mode. The select module is then used to wait for incoming characters.
CATEGORY: library