A small utility class to read single characters from standard input, on both Windows and UNIX systems. It provides a getch() function-like instance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 | class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
|
Comments
old python versions have to include TERMIOS. If you use an old python version (e.g. 1.5) you have to include "TERMIOS" additionally to "termios" and the "TCSADRAIN" is found in "TERMIOS".
extended for MacOS.
(comment continued...)
(...continued from previous comment)
</pre>
erratum for MacOS modification.
updated for OS X. The following code (along with the _GetUnix and _GetWindows above) gives the correct getch behavior whether imported in the pythonIDE or in a Terminal script on the Mac. The order of trial imports is changed in _Getch because when in the IDE, the Unix import was succeeding. A single line in the _GetMacCarbon was added to see if the Carbon module has the Evt method. When the import succeeds when in the Terminal, the Carbon library there does not have the Evt method and so the import fails and the _GetchUnix() line is executed.
I also found that the curses snippet at < http://www.pythonapocrypha.com/Chapter22/Chapter22.shtml > works in the Terminal but will cause the pythonIDE to quit without warning if you run it there.
getch with IDLE. I was unable to make this work in IDLE on OSX. I guess because of what IDLE seems to do to stdio. I always got "AttributeError".
Carbon less invasive? Hi, I tried the code on linux and got " ImportError: No module named Carbon"
You should wrap the carbon loading in a "try:" I suppose (I'm not experienced enough to post an example, as I eg. don't know what to write into "except ImportError:" if I want nothing to happen.
This should do the trick:
Sign in to comment