Created
August 7, 2016 20:56
-
-
Save martinapugliese/04b95c1dc972f664f36e6157c4250010 to your computer and use it in GitHub Desktop.
A class for styled printing (coloured/styled text, time of execution available), attributes combinable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright (C) 2016 Martina Pugliese | |
# Imports | |
from datetime import datetime | |
# #################### ANSI Escape codes for terminal ######################### | |
codes_dict = { | |
# Text colours | |
't_black': '\033[30m', | |
't_red': '\033[31m', | |
't_green': '\033[32m', | |
't_yellow': '\033[33m', | |
't_blue': '\033[34m', | |
't_magenta': '\033[35m', | |
't_cyan': '\033[36m', | |
't_white': '\033[37m', | |
# Background colours | |
'b_black': '\033[40m', | |
'b_red': '\033[41m', | |
'b_green': '\033[42m', | |
'b_yellow': '\033[43m', | |
'b_blue': '\033[44m', | |
'b_magenta': '\033[45m', | |
'b_cyan': '\033[46m', | |
'b_white': '\033[47m', | |
# Special | |
'black_on_white': '\033[7m', | |
# Text styles | |
'bold': '\033[1m', | |
'underline': '\033[4m', | |
'normal': '\033[0m' | |
} | |
############################################################################### | |
class StyledPrinter(object): | |
""" | |
Class for styled print on stdout. Can attach text attributes from dict above and combine them to obtain desided style. | |
""" | |
def __init__(self): | |
self.codes_dict = codes_dict | |
def show_available_codes(self): | |
"""Print the available ANSI escape codes.""" | |
print self.codes_dict.keys() | |
def create_time_text(self, text, text_attrs=None): | |
"""Print the time of execution (in green) plus the text (with chosen optional attributes). | |
text_attrs has to be a list otherwise it prints in normal black.""" | |
if text_attrs and isinstance(text_attrs, list): | |
attr_string = '' | |
for attr in text_attrs: | |
attr_string += self.codes_dict[attr] | |
print self.codes_dict['t_green'] + '[' + \ | |
datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '] ' + \ | |
attr_string + text + self.codes_dict['normal'] | |
else: | |
print self.codes_dict['t_green'] + '[' + \ | |
datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '] ' + \ | |
self.codes_dict['normal'] + text + self.codes_dict['normal'] | |
def create_coloured_text(self, text, text_attrs=None): | |
"""Print text (in chosen colour and with optional chosen style). | |
text_attrs has to be a list otherwise it prints in normal black.""" | |
if text_attrs and isinstance(text_attrs, list): | |
attr_string = '' | |
for attr in text_attrs: | |
attr_string += self.codes_dict[attr] | |
print attr_string + text + self.codes_dict['normal'] | |
else: | |
print text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment