Created
April 1, 2022 15:18
-
-
Save joshbduncan/a6a01583292cc7564236a3a1898ce173 to your computer and use it in GitHub Desktop.
Simple Progress Spinner Using Python Generators
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 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