~ekez/tui-webpage

tui-webpage/examples/getch.py -rw-r--r-- 1.7 KiB
e07ce7c9Zeke Medley Add class feedback spreadsheet links 7 hours ago
                                                                                
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# This file exports a function called `getch` which will read a single
# character of user input from the terminal without waiting for a
# newline. In theory this ought to be Windows compatable but I am
# unable to verify this as I (Zeke) do not own a Windows machine.
#
# To use this file place it in the same directory as the file that you
# would like to use it in is in and add:
# ```
# from <NAME OF THIS FILE> import getch
# ```
#
# Note that when using this `getch` function sending ^C to the console
# will not cause the program to end like you might expect as the ^C
# interrupt will be read in. To avoid a program that is impossible to
# exit you may want to configure a specific character that when read
# in will terminate the program.

class _Getch:
    """Gets a single character from standard input.  Does not echo to
    the screen.

    Source:
    https://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
    """
    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()