00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 import sys
00011
00012
00013
00014
00015
00016
00017 def console_has_colours(stream):
00018 if not hasattr(stream, "isatty"):
00019 return False
00020 if not stream.isatty():
00021 return False
00022 try:
00023 import curses
00024 curses.setupterm()
00025 return curses.tigetnum("colors") > 2
00026 except:
00027
00028 return False
00029
00030 has_colours = console_has_colours(sys.stdout)
00031 if has_colours:
00032
00033 reset = "\x1b[0m"
00034 bold = "\x1b[%sm" % '1'
00035 black, red, green, yellow, blue, magenta, cyan, white = ["\x1b[%sm" % str(i) for i in range(30, 38)]
00036 bold_black, bold_red, bold_green, bold_yellow, bold_blue, bold_magenta, bold_cyan, bold_white = ["\x1b[%sm" % ('1;' + str(i)) for i in range(30, 38)]
00037 else:
00038 reset = ""
00039 bold = ""
00040 black, red, green, yellow, blue, magenta, cyan, white = ["" for i in range(30, 38)]
00041 bold_black, bold_red, bold_green, bold_yellow, bold_blue, bold_magenta, bold_cyan, bold_white = ["" for i in range(30, 38)]
00042
00043 colours = [
00044 bold,
00045 black, red, green, yellow, blue, magenta, cyan, white,
00046 bold_black, bold_red, bold_green, bold_yellow, bold_blue, bold_magenta, bold_cyan, bold_white
00047 ]
00048
00049
00050 def pretty_print(msg, colour=white):
00051 if has_colours:
00052 seq = colour + msg + reset
00053 sys.stdout.write(seq)
00054 else:
00055 sys.stdout.write(msg)
00056
00057
00058 def pretty_println(msg, colour=white):
00059 if has_colours:
00060 seq = colour + msg + reset
00061 sys.stdout.write(seq)
00062 sys.stdout.write("\n")
00063 else:
00064 sys.stdout.write(msg)
00065
00066
00067
00068
00069
00070
00071
00072 def debug(msg):
00073 print(green + msg + reset)
00074
00075
00076 def warning(msg):
00077 print(yellow + msg + reset)
00078
00079
00080 def error(msg):
00081 print(red + msg + reset)
00082
00083
00084 def logdebug(message):
00085 print(green + "[debug] " + message + reset)
00086
00087
00088 def loginfo(message):
00089 print("[info] " + message)
00090
00091
00092 def logwarn(message):
00093 print(yellow + "[warning] " + message + reset)
00094
00095
00096 def logerror(message):
00097 print(red + "[error] " + message + reset)
00098
00099
00100 def logfatal(message):
00101 print(bold_red + "[error] " + message + reset)
00102
00103
00104
00105
00106
00107
00108 if __name__ == '__main__':
00109 for colour in colours:
00110 pretty_print("dude\n", colour)
00111 logdebug("info message")
00112 logwarn("warning message")
00113 logerror("error message")
00114 logfatal("fatal message")
00115 pretty_print("red\n", red)
00116 print("some normal text")
00117 print(cyan + " Name" + reset + ": " + yellow + "Dude" + reset)