Skip to content

Instantly share code, notes, and snippets.

@konradkonrad
Last active April 9, 2018 15:53
Show Gist options
  • Save konradkonrad/adff5bcefa3cfe2303518cce696ba7de to your computer and use it in GitHub Desktop.
Save konradkonrad/adff5bcefa3cfe2303518cce696ba7de to your computer and use it in GitHub Desktop.
minimal statusbar watcher
import sys
import time
def reprint(msg):
"""Print msg from beginning of last line."""
sys.stdout.write('\r')
sys.stdout.write(str(msg))
sys.stdout.flush()
def watch(fn, update=0.25):
"""Print the result of `fn` every `update` to last line of stdout."""
result = fn()
while result:
reprint(result)
time.sleep(update)
result = fn()
if __name__ == '__main__':
# Example with datetime.datetime.now()
import signal
import datetime
# on catching SIGINT write a newline and exit
signal.signal(signal.SIGINT, lambda *_: print() or sys.exit(0))
# run watcher with a .5 s update interval
watch(datetime.datetime.now, update=.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment