This repository has been archived by the owner on Aug 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cprint.py
79 lines (69 loc) · 2.15 KB
/
cprint.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
# -*- coding: utf-8 -*-
"""
Color print function.
Use: cprint('text', colorize=True) or
cprint('text %s' % var, colorize=True)
Can't: cprint('text', var, colorize=True)
"""
class Stack:
def __init__(self):
self.items = []
def isempty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop() if self.items else ''
def peek(self):
return self.items[len(self.items)-1] if self.items else None
def size(self):
return len(self.items)
def cprint(text, colorize=False, noprint=False):
"""
Function for color print.
Use: cprint('text', colorize=True) or
cprint('text %s' % var, colorize=True) or
cprint('text %s %s %s' % (var1, var2, var3), colorize=True)
Can't use: cprint('text', var, colorize=True)
:param text: String like 'hello world'
:param colorize: Boolean
"""
import re
s = Stack()
colors = {None: '\033[0m',
'[black]': '\033[30m',
'[red]': '\033[31m',
'[green]': '\033[32m',
'[yellow]': '\033[33m',
'[blue]': '\033[34m',
'[purple]': '\033[35m',
'[cyan]': '\033[36m',
'[underline]': '\033[4m'}
if colorize:
text = text.split('[/]')
_text = ''
for block in text:
tags = re.findall(r'\[[^\]]{,}\]', block)
for tag in tags:
if tag in colors:
block = block.replace(tag, colors[tag])
s.push(tag)
if s.peek() in ['[underline]']:
_text += block + colors[s.peek()]+'\033[24m'
s.pop()
else:
s.pop()
_text += block + colors[s.peek()]
text = _text
text = re.sub(r'\s+^\n', ' ', text)
if noprint:
return text
else:
print text
else:
text = re.sub(r'\[.*?\]', '', text)
text = re.sub(r'\s+^\n', ' ', text)
if noprint:
return text
else:
print text