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
|
from os import linesep
# we can also do print(colored('green', msg), end='') for example...
# printc helps if You have a global color_enabled flag in Your program
def printc(color, msg, no_newline=False, enable_color=False):
"""like print but with color support (if enabled!)"""
ret = str()
if enable_color:
ret += colored(color, msg)
else:
ret += msg
if no_newline:
end = ''
else:
end = linesep
print(ret, end=end, flush=True)
return ret
def colored(color, msg):
"""returns msg in ANSI color"""
ret = str()
c = 'default'
if color == 'red':
c = '31'
elif color == 'green':
c = '32'
elif color == 'yellow':
c = '33'
elif color == 'blue':
c = '34'
elif color == 'magenta':
c = '35'
elif color == 'cyan':
c = '36'
if c is not 'default':
# set color
ret += '\033[0;' + c + 'm'
ret += msg
# reset color
ret += '\033[0m'
return ret
# When data contains ANSI color escape codes convert them to BBcode format
# e.g.: Foo bar baz [\033[0;31m + text + [\033[0m
# where 31 can be 31..36 31=red, 32=green,
# 33=yellow, 34=blue, 35=magenta, 36-cyan
# 0 resets back to standard
# we can map those three parts to [color=#abcdef] + text + [/color]
def convert_ansi_to_bbcode_colors(instr):
"""convert ansi escape sequences in a string to bbcode tags"""
ansi_red = '\033[0;31m'
ansi_green = '\033[0;32m'
ansi_yellow = '\033[0;33m'
ansi_blue = '\033[0;34m'
ansi_magenta = '\033[0;35m'
ansi_cyan = '\033[0;36m'
ansi_end = '\033[0m'
bb_red = '[color=#FF0000]'
bb_green = '[color=#00FF00]'
bb_yellow = '[color=#FFFF00]'
bb_blue = '[color=#0000FF]'
bb_magenta = '[color=#FF00FF]'
bb_cyan = '[color=#00FFFF]'
bb_end = '[/color]'
return instr.replace(ansi_red, bb_red) \
.replace(ansi_green, bb_green) \
.replace(ansi_yellow, bb_yellow) \
.replace(ansi_blue, bb_blue) \
.replace(ansi_magenta, bb_magenta) \
.replace(ansi_cyan, bb_cyan) \
.replace(ansi_end, bb_end)
|