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()
|
Tags: sysadmin
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:
With regards to Windows, may I suggest the following?
using curses with unicode
Does this work on windows? (Note: this assumes utf8 input.)
Anything that can stand the test of time deserves praise. This is one piece of code that is definitely in that category.
Well done and......
......many thanks Danny.
I have "pinched" part of it for my usage and made a pointer to this code snippet in my code too...
Here:-
http://code.activestate.com/recipes/577728-simpletron3xpy-game-to-demo-xy-drawing-using-the-k/?in=user-4177147
Thanks again and voted it up another place...
Bazza, G0LCU.
BTW, I will soon be uploading a Morse Practice Oscillator using you code too... ;o)
I used the select module for a Non-Blocking implementation on Linux. This times out in (5 seconds here) if no input is received. Particularly useful when used in a thread, so that the getch call is non-blocking and will allow the thread to exit cleanly
{{{ http://code.activestate.com/recipes/134892/ (r2)
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()
class _GetchUnix: def __init__(self): import tty, sys
class _GetchWindows: def __init__(self): import msvcrt
getch = _Getch()
end of http://code.activestate.com/recipes/134892/ }}}
I have problem with the main code in linux.
It returns:
And of course it doesn't wait to get any character.
I used it in this way:
do this: print getch.impl()
Hi, I'm 14 years old. My name's william. I've being making this program and it works fine in windows but not linux? I am running Linux Arch (E17 desktop environment) with both Python3 and Python2 installed. There are no errors but when I start the program, it prints it but when I push the arrow keys nothing happens?
Here it is: https://github.com/Gogo-Programming/You-wake-up
And here is what it looks like on linux (And yes my terminal has red text ^): http://www.enlightenment.org/ss/e-52d4d7716efc53.35386887.png
Help much appreciated (Im a bit of a noob with python so sorry if this is a stupid question to you pros)
Hi there!!
I needed this functionality too and it was quite difficult to follow this thread. Because of that, I created the readchar library (https://pypi.python.org/pypi/readchar) in order to make it reusable.
I mention this thread, but I changed the license to MIT in order to allow everyone to use and change it everywhere.
Please, if you want to change anything or to test it in OSX/Windows (only GNU/Linux is being tested right now), please, send your comments, add an issue or send your pull requests!
Thank you very much!
Hi,
I try to use this example to read a single character from stdin but get the error
AttributeError: _Getch instance has no attribute '__trunc__'
It is used in the following code
Best Regards, Mikael
Thank you so much Danny Yoo for the original post, and C Smith for the updates for Mac. It truly makes it a nice cross-platform piece of code.