Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Progress Spinner Using Python Context Manager and Generators
import sys
import time
from contextlib import contextmanager
def spinner_indicator(msg):
ticks = ["-", "\\", "|", "/"]
i = 0
while True:
tick = ticks[i % len(ticks)]
yield sys.stdout.write(f"\r{tick} {msg}")
i += 1
@contextmanager
def spinner(msg="working..."):
error = False
try:
yield spinner_indicator(msg)
except Exception:
error = True
raise
except GeneratorExit:
sys.stdout.write("\r✔\n")
finally:
if error:
sys.stdout.write("\r𝘅\n")
else:
sys.stdout.write("\r✔\n")
sys.stdout.flush()
if __name__ == "__main__":
jobs = ["sample job", "another job", "job with an exception"]
for job in jobs:
with spinner(f"processing {job}...") as p:
for i in range(10):
next(p)
time.sleep(0.25)
if "exception" in job and i == 6:
raise ValueError("test exception")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment