00001
00002
00003
00004
00005
00006
00007 import sys
00008
00009
00010
00011
00012
00013
00014 def console_has_colours(stream):
00015 if not hasattr(stream, "isatty"):
00016 return False
00017 if not stream.isatty():
00018 return False
00019 try:
00020 import curses
00021 curses.setupterm()
00022 return curses.tigetnum("colors") > 2
00023 except:
00024
00025 return False
00026
00027 has_colours = console_has_colours(sys.stdout)
00028
00029 reset = "\x1b[0m"
00030
00031 bold = '1'
00032 black, red, green, yellow, blue, magenta, cyan, white = [str(i) for i in range(30, 38)]
00033 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)]
00034 colours = [
00035 bold,
00036 black, red, green, yellow, blue, magenta, cyan, white,
00037 bold_black, bold_red, bold_green, bold_yellow, bold_blue, bold_magenta, bold_cyan, bold_white
00038 ]
00039
00040
00041 def pretty_print(msg, colour=white):
00042 if has_colours:
00043 seq = "\x1b[%sm" % (colour) + msg + reset
00044 sys.stdout.write(seq)
00045 else:
00046 sys.stdout.write(msg)
00047
00048
00049 def pretty_println(msg, colour=white):
00050 if has_colours:
00051 seq = "\x1b[%sm" % (colour) + msg + reset
00052 sys.stdout.write(seq)
00053 sys.stdout.write("\n")
00054 else:
00055 sys.stdout.write(msg)
00056
00057
00058
00059
00060
00061
00062
00063 def debug(msg):
00064 pretty_print("%s\n" % msg, green)
00065
00066
00067 def warning(msg):
00068 pretty_print("%s\n" % msg, yellow)
00069
00070
00071 def error(msg):
00072 pretty_print("%s\n" % msg, red)
00073
00074
00075 def logdebug(message):
00076 pretty_print("[debug] " + message + "\n", blue)
00077
00078
00079 def loginfo(message):
00080 pretty_print("[info] " + 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")