-
Notifications
You must be signed in to change notification settings - Fork 3
/
TermColors.py
54 lines (40 loc) · 1.43 KB
/
TermColors.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
################################################################################
# TermColors - python utility for setting terminal colors.
#
# Version 1
# Matthew Malensek <[email protected]>
################################################################################
import os, re, sys, termios, tty
class TermColors:
prefix = ''
suffix = ''
# tmux and screen require a DCS sequence before sending commands:
if os.environ['TERM'][:6] == 'screen':
if 'TMUX' in os.environ:
prefix = '\x1bPtmux;\x1b'
else:
prefix = '\x1bP'
suffix = '\x1b\\'
ttyname = os.ttyname(0)
fd = open(ttyname, 'r+')
def write(self, string):
self.fd.write(self.prefix + string + self.suffix)
def get(self, color):
oldsettings = termios.tcgetattr(self.fd)
tty.setraw(self.fd, termios.TCSANOW)
self.write("\033]4;" + str(color) + ";?\a")
response = ""
char = ""
while char != '\a':
response += char
char = self.fd.read(1)
if char == "":
break
r = re.compile(r'rgb:(..).*/(..).*/(..).*')
termios.tcsetattr(self.fd, termios.TCSADRAIN, oldsettings)
return r.findall(response)[0]
def set(self, color, rgb):
self.write("\033]4;" + str(color) + ";rgb:" +
rgb[0] + "/" + rgb[1] + "/" + rgb[2] + "\a")
def close(self):
self.fd.close()