Last active
April 9, 2018 15:53
-
-
Save konradkonrad/adff5bcefa3cfe2303518cce696ba7de to your computer and use it in GitHub Desktop.
minimal statusbar watcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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