-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterm.py
92 lines (74 loc) · 1.75 KB
/
term.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
import os, sys, atexit
def is_nt():
return os.name == 'nt'
try:
import colorama
colorama.init()
except:
try:
import tendo.ansiterm
except:
pass
if is_nt():
import msvcrt
else:
import termios, fcntl
class Term:
KEY_LEFT = ('\033[D', '\xe0K')
KEY_RIGHT = ('\033[C', '\xe0M')
KEY_DOWN = ('\033[B', '\xe0P')
def __init__(self):
if is_nt():
self.init_nt()
else:
self.init_posix()
def init_posix(self):
os.system('clear')
self.fd = sys.stdin.fileno()
self.oldterm = termios.tcgetattr(self.fd)
self.newattr = termios.tcgetattr(self.fd)
self.newattr[3] = self.newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr)
self.oldflags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)
atexit.register(self.cleanup_posix)
def block(self):
if is_nt():
return
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.oldterm)
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags)
def unblock(self):
if is_nt():
return
termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr)
fcntl.fcntl(self.fd, fcntl.F_SETFL, self.oldflags | os.O_NONBLOCK)
def cleanup_posix(self):
self.block()
print("\033[?25h")
def init_nt(self):
os.system('cls')
atexit.register(self.cleanup_nt)
def cleanup_nt(self):
print("\033[?25h")
def getch(self):
ret = ""
c = " "
if is_nt():
while c != "":
if msvcrt.kbhit():
c = msvcrt.getch()
ret += ''.join(chr(x) for x in c)
else:
c = ""
else:
while c != "":
c = sys.stdin.read(1)
ret += c
return ret
def display(self, s):
self.block()
self.clear()
print(str(s))
self.unblock()
def clear(self):
print('\033[?25l\033[J\033[H')