python可以指定print字体颜色,代码:
s e l f L o g . p y selfLog.py selfLog.py
import config
import time, traceback
from colorama import init
init(autoreset=True)
def getColor(rank):
manner = 1
foreground = 30 # [30, 37]
background = 47 # [40, 47]
foreground += rank % 8
background -= rank % 8
# color = '\033[%d;%d;%dm' % (manner, foreground, background)
color = '\033[%d;%dm' % (manner, foreground)
return color
def selfLog(rank, *logs):
if rank < config.selfLogRank:
return
tracebackinfo = str(traceback.extract_stack()[0])
begin = tracebackinfo.index('file')
end = tracebackinfo.rindex(' in')
tracebackinfo = tracebackinfo[begin:end]
times = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime())
print('-- %s, %s' % (tracebackinfo, times))
color = getColor(rank)
for log in logs:
print(' %s%s' % (color, log), end=' ')
print()
c o n f i g . p y config.py config.py
selfLogRank = 0
m a i n . p y main.py main.py
from selfLog import selfLog
if __name__ == '__main__':
selfLog(1, 'Reading image...', 'info_1', 'info_2')
selfLog(3, 'Failed to read image!', 'info_1')
调用时第一个参数rank不小于config.selfLogRank才会输出。
参考