Skip to content

Instantly share code, notes, and snippets.

@Djexus
Created January 5, 2012 01:26
Show Gist options
  • Save Djexus/1563212 to your computer and use it in GitHub Desktop.
Save Djexus/1563212 to your computer and use it in GitHub Desktop.
Decorator which adds statusline to functions
import sys
BUSYMSG = '\033[1;34m[\033[1;m\033[1;36mBUSY\033[1;m\033[1;34m]\033[1;m'
DONEMSG = '\033[1;34m[\033[1;m\033[1;35mDONE\033[1;m\033[1;34m]\033[1;m'
FAILMSG = '\033[1;34m[\033[1;m\033[1;31mFAIL\033[1;m\033[1;34m]\033[1;m'
def showstatus(message=None, length=50):
'''
Decorator which adds the statusline during function's execution,
printing '[message]spaces[BUSY]' while it's running, and, when
it stops, '[message]spaces[DONE]'. If an exception occurrs it
silents it and print '[message]space[FAIL]'. Spaces are obtained
using [lenght]-len([message]). If not specified, message is the
function's name. Default length is 50.
Usage:
>>> from urllib.request import urlopen
>>> openurl = showstatus('Opening url')(urlopen)
'''
def decorator(function):
def wrapper(*args, **kwargs):
nonlocal message
message = message or function.__name__
spaces = ' ' * (length - len(message))
result = None
sys.stdout.write('%s%s' % (message, spaces))
sys.stdout.write('%s' % BUSYMSG)
sys.stdout.flush()
try:
result = function(*args, **kwargs)
except:
sys.stdout.write('\b \b' * 6)
sys.stdout.write(('%s\n' % FAILMSG))
else:
sys.stdout.write('\b \b' * 6)
sys.stdout.write(('%s\n' % DONEMSG))
sys.stdout.flush()
return result
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment