-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_getter.py
executable file
·159 lines (128 loc) · 4.49 KB
/
key_getter.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
'''
Author: Yu Lou
Date: 2017-02-23
Based on the answer by @enrico.bacis in http://stackoverflow.com/a/13207724/4398908
and @Phylliida in http://stackoverflow.com/a/31736883/4398908
'''
# Import modules
try:
try:
import termios, fcntl, sys, os, curses # Import modules for Linux
except ImportError:
import msvcrt # Import module for Windows
except ImportError:
raise Exception('This platform is not supported.')
class KeyGetterLinux:
'''
Implemented kbhit(), getch() and getchar() in Linux.
Tested on Ubuntu 16.10(Linux 4.8.0), Python 2.7.12 and Python 3.5.2
'''
def __init__(self):
self.buffer = '' # A buffer to store the character read by kbhit
self.started = False # Whether initialization is complete
def kbhit(self, echo = False):
'''
Return whether a key is hitten.
'''
if not self.buffer:
if echo:
self.buffer = self.getchar(block = False)
else:
self.buffer = self.getch(block = False)
return bool(self.buffer)
def getch(self, block = True):
'''
Return a single character without echo.
If block is False and no input is currently available, return an empty string without waiting.
'''
try:
curses.initscr()
curses.noecho()
return self.getchar(block)
finally:
curses.endwin()
def getchar(self, block = True):
'''
Return a single character and echo.
If block is False and no input is currently available, return an empty string without waiting.
'''
self._start()
try:
return self._getchar(block)
finally:
self._stop()
def _getchar(self, block = True):
'''
Return a single character and echo.
If block is False and no input is currently available, return a empty string without waiting.
Should be called between self._start() and self._end()
'''
assert self.started, ('_getchar() is called before _start()')
# Change the terminal setting
if block:
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags & ~os.O_NONBLOCK)
else:
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags | os.O_NONBLOCK)
if self.buffer: # Use the character in buffer first
result = self.buffer
self.buffer = ''
else:
try:
result = sys.stdin.read(1)
except IOError: # In python 2.7, using read() when no input is available will result in IOError.
return ''
return result
def _start(self):
'''
Initialize the terminal.
'''
assert not self.started, '_start() is called twice'
self.fd = sys.stdin.fileno()
self.old_attr = termios.tcgetattr(self.fd)
new_attr = termios.tcgetattr(self.fd)
new_attr[3] = new_attr[3] & ~termios.ICANON
termios.tcsetattr(self.fd, termios.TCSANOW, new_attr)
self.old_flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
self.started = True
def _stop(self):
'''
Restore the terminal.
'''
assert self.started, '_start() is not called'
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_attr)
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags)
self.started = False
# Magic functions for context manager
def __enter__(self):
self._start()
self.getchar = self._getchar # No need for self._start() now
return self
def __exit__(self, type, value, traceback):
self._stop()
return False
class KeyGetterWindows:
'''
kbhit() and getchar() in Windows.
Tested on Windows 7 64 bit, Python 2.7.1
'''
def kbhit(self, echo):
return msvcrt.kbhit()
def getchar(self, block = True):
if not block and not msvcrt.kbhit():
return ''
return msvcrt.getchar()
def getch(self, block = True):
if not block and not msvcrt.kbhit():
return ''
return msvcrt.getch()
_getchar = getchar
# Magic functions for context manager
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False
try:
import termios
KeyGetter = KeyGetterLinux # Use KeyGetterLinux if termios exists
except ImportError:
KeyGetter = KeyGetterWindows # Use KeyGetterWindows otherwise