Skip to content

Instantly share code, notes, and snippets.

@benkehoe
Last active May 22, 2018 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkehoe/c5812f8bfb1b4ee186f1 to your computer and use it in GitHub Desktop.
Save benkehoe/c5812f8bfb1b4ee186f1 to your computer and use it in GitHub Desktop.
Python stdin char getter
"""
Copyright 2018 Ben Kehoe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
def getch(prompt=None, yesno=False, on_ctrl_c=None):
"""Gets a single character from standard input. Does not echo to the screen.
on_ctrl_c can be an Exception (e.g., KeyboardInterrupt) to raise, or a
callable taking no arguments.
Example usage:
while True:
ch = getch('Hit a key')
if getch.is_ctrl_c(ch):
if getch.yesno('Are you sure you want to exit?'):
break
print 'got ch:', ch
"""
import sys
def is_ctrl_c(ch):
return ord(ch) == 3
if not hasattr(getch, 'is_ctrl_c'):
setattr(getch, 'is_ctrl_c', is_ctrl_c)
if not hasattr(getch, '_impl'):
try:
msvcrt = __import__('msvcrt')
impl = msvcrt.getch
except ImportError:
def getch_unix():
termios = __import__('termios')
tty = __import__('tty')
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
impl = getch_unix
setattr(getch, '_impl', impl)
if prompt:
sys.stdout.write(prompt)
sys.stdout.flush()
ch = getch._impl()
if prompt:
sys.stdout.write('\n')
sys.stdout.flush()
import inspect
if is_ctrl_c(ch) and on_ctrl_c:
if (isinstance(on_ctrl_c, BaseException)
or (inspect.isclass(on_ctrl_c) and issubclass(on_ctrl_c, BaseException))):
raise on_ctrl_c
on_ctrl_c()
if yesno:
return ch.lower() == 'y'
else:
return ch
setattr(getch, 'yesno', lambda prompt=None, on_ctrl_c=None: getch(prompt=prompt, yesno=True, on_ctrl_c=on_ctrl_c))
setattr(getch, 'is_ctrl_c', lambda ch: ord(ch) == 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment