Skip to content

Instantly share code, notes, and snippets.

@joshbduncan
Created April 1, 2022 15:18
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/a6a01583292cc7564236a3a1898ce173 to your computer and use it in GitHub Desktop.
Save joshbduncan/a6a01583292cc7564236a3a1898ce173 to your computer and use it in GitHub Desktop.
Simple Progress Spinner Using Python Generators
import sys
import time
def spinner(msg="working..."):
i = 0
ticks = ["-", "\\", "|", "/"]
try:
while True:
tick = ticks[i % len(ticks)]
yield sys.stdout.write(f"\r{tick} {msg}")
i += 1
except Exception:
sys.stdout.write("\r𝘅\n")
raise
except GeneratorExit:
sys.stdout.write("\r✔\n")
finally:
sys.stdout.flush()
if __name__ == "__main__":
jobs = ["sample job", "another job", "job with an exception"]
for job in jobs:
s = spinner(f"processing {job}...")
try:
for i in range(10):
next(s)
time.sleep(0.25)
if "exception" in job and i == 6:
raise ValueError("test exception")
except Exception as e:
s.throw(e)
finally:
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment