Created
July 30, 2012 19:11
-
-
Save empiricalthought/3209245 to your computer and use it in GitHub Desktop.
Python 3 ASCII spinner for progress feedback
This file contains 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 itertools | |
import sys | |
def spinner(granularity): | |
"""Wraps a function in an ASCII spinner display loop. granularity | |
represents the number of times the function should be called | |
before moving the spinner.""" | |
spinner_chars = itertools.cycle("\|/-") | |
def make_spinner(f): | |
calls = 0 | |
def g(*args, **kwargs): | |
nonlocal calls | |
nonlocal granularity | |
result = f(*args, **kwargs) | |
if calls == 0: | |
sys.stdout.write("\b" + next(spinner_chars)) | |
sys.stdout.flush() | |
calls = (calls + 1) % granularity | |
return result | |
return g | |
return make_spinner | |
# example: | |
# import time | |
# @spinner(10) | |
# def process_chunk(): | |
# time.sleep(.1) | |
# sys.stdout.write("running... ") | |
# while True: | |
# process_chunk() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment