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