Skip to content

Instantly share code, notes, and snippets.

@empiricalthought
Created July 30, 2012 19:11
Show Gist options
  • Save empiricalthought/3209245 to your computer and use it in GitHub Desktop.
Save empiricalthought/3209245 to your computer and use it in GitHub Desktop.
Python 3 ASCII spinner for progress feedback
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