Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!nntp.club.cc.cmu.edu!micro-heart-of-gold.mit.edu!bloom-beacon.mit.edu!bloom-beacon.mit.edu!panix!not-for-mail From: Grant Edwards Newsgroups: comp.lang.python Subject: Re: Keypress Input Date: Mon, 15 Jun 2015 15:22:52 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 61 Message-ID: References: NNTP-Posting-Host: 67-130-15-94.dia.static.qwest.net X-Trace: reader1.panix.com 1434381772 14074 67.130.15.94 (15 Jun 2015 15:22:52 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Mon, 15 Jun 2015 15:22:52 +0000 (UTC) User-Agent: slrn/1.0.2 (Linux) Xref: csiph.com comp.lang.python:92639 On 2015-06-15, Oscar Benjamin wrote: > Note that going into raw mode has other implications such as not > being able to exit your program with ctrl-c or suspend with ctrl-z > etc. You can explicitly process those kinds of contrl keys with > something like: > > while True: > key = getch() > if 1 <= ord(key) <= 26: > ctrl_key = chr(ord(key) + 64) > print("ctrl-%c" % ctrl_key) > if ctrl_key == 'C': > break > else: > print("key: '%c'" % key) It's probably better (at least on Linux) to just enable handling of those characters in by setting the ISIG lflag: def getch(): fd = sys.stdin.fileno() oldsettings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) # enable handling of ctrl-C, ctrl-Z, etc. attr = termios.tcgetattr(fd) attr[3] |= termios.ISIG termios.tcsetattr(fd,termios.TCSANOW,attr) c = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings) return c It would be a bit cleaner if the termios module supported the the cfmakeraw(3) function, then you could do it this way and save a couple of system calls: def getch(): fd = sys.stdin.fileno() oldsettings = termios.tcgetattr(fd) try: newsettings = termios.makeraw(oldsettings) newsettings[3] |= termios.ISIG termios.tcsetattr(fd,termios.TCSANOW,newsettings) c = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings) return c [I'm a bit surprised that after all these years using literal integers to index into the attribute list is the "right" way.] -- Grant Edwards grant.b.edwards Yow! Well, O.K. at I'll compromise with my gmail.com principles because of EXISTENTIAL DESPAIR!