Skip to content

Instantly share code, notes, and snippets.

@statico
Created August 20, 2010 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statico/539863 to your computer and use it in GitHub Desktop.
Save statico/539863 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#
# fancyoutput.py - quick functions to make script output pretty
#
# by Ian Langworth, 2010
#
# This code is in the public domain.
#
import sys
import os
import time
__all__ = ('write', 'clear', 'header', 'debug', 'log', 'warn', 'error',
'begin', 'tick', 'end')
BLACK = '\x1b[30m'
RED = '\x1b[31m'
GREEN = '\x1b[32m'
YELLOW = '\x1b[33m'
BLUE = '\x1b[34m'
MAGENTA = '\x1b[35m'
CYAN = '\x1b[36m'
WHITE = '\x1b[37m'
BOLD = '\x1b[1m'
NORMAL = '\x1b[0m'
CLEAR_SCREEN = '\x1b[2J\x1b[H'
CLEAR_LINE = '\x1b[999D\x1b[2K'
_current_line = ''
_total = 0
_progress_count = 0
_prefix = ''
def write(string, *args):
if args:
sys.stderr.write(string % args)
else:
sys.stderr.write(string)
sys.stderr.flush()
def clear():
write(CLEAR_SCREEN)
def header(string):
global _current_line
line = '-' * 80
write(CLEAR_LINE + BLUE)
write('%s\n%s\n%s\n' % (line, string, line))
write(NORMAL)
write(_current_line)
def _mode(mode, color):
return '%s%7s%s ' % (color, '[' + mode + ']', NORMAL)
def _log(mode, color, string, *args):
global _current_line
write(CLEAR_LINE)
write(_mode(mode, color))
write(string, *args)
write('\n')
write(_current_line)
def debug(string, *args):
_log('DEBUG', BOLD + BLACK, string, *args)
def log(string, *args):
_log('INFO', GREEN, string, *args)
def warn(string, *args):
_log('WARN', YELLOW, string, *args)
def error(string, *args):
_log('ERROR', RED, string, *args)
def _update():
write(CLEAR_LINE + _current_line)
def begin(string, *args, **kwargs):
global _current_line, _count, _total, _prefix
_count = 0
_total = float(kwargs.get('items', 0))
_prefix = _mode('INFO', GREEN) + (string % args)
_current_line = _prefix
if _total:
_current_line += ' %2d%% ' % 0
_update()
def tick():
global _current_line, _count, _total, _prefix
if _total:
_count += 1
_current_line = _prefix + ' %3d%% ' % (_count / _total * 100)
else:
_current_line += '.'
_update()
def end():
global _current_line, _count, _total, _prefix
if _total:
_count = _total - 1
tick()
write('\n')
else:
write(' done.\n')
_total = 0
_current_line = ''
if __name__ == '__main__':
clear()
header('Testing')
debug('This isn\'t important.')
log('This is something userful...')
warn('But watch out for this')
error('And this is bad')
begin('Checking progress...', items=20)
for i in range(20):
tick()
if not (i % 5):
log('A number: %s', i)
time.sleep(.1)
end()
begin('Starting counter...')
for i in range(20):
tick()
if not (i % 5):
log('A number: %s', i)
time.sleep(.1)
end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment