Skip to content

Instantly share code, notes, and snippets.

@joshbduncan
Created April 1, 2022 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshbduncan/d47726aa351e467d849748e3de607943 to your computer and use it in GitHub Desktop.
Save joshbduncan/d47726aa351e467d849748e3de607943 to your computer and use it in GitHub Desktop.
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