-
-
Save ivanignatiev/568ba85a8e57bb2b6004dadb09fd779e to your computer and use it in GitHub Desktop.
A Simple Loading Animation Decorator and Context Manger for the Command Line Using Python 3
This file contains hidden or 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
""" | |
This program is designed to create | |
and animate a simple loading animation. | |
""" | |
from sys import stdout as terminal | |
from time import sleep | |
from itertools import cycle | |
from threading import Thread | |
from contextlib import contextmanager | |
from timeit import default_timer as timer | |
@contextmanager | |
def loading_animation(running_text: str = "Running", finished_text: str = "Done!"): | |
done = False | |
def animation(): | |
timer_start = timer() | |
for c in cycle(["|", "/", "-", "\\"]): | |
if done: | |
break | |
time_in_sec = timer() - timer_start | |
text_to_display = f"\r{running_text} " + "{:.2f}".format(time_in_sec) + "s " + c | |
terminal.write(text_to_display) | |
terminal.flush() | |
sleep(0.1) | |
diff = len(text_to_display) - len(finished_text) + 2 | |
spaces = " " * diff if diff > 0 else "" | |
terminal.write(f"\r{finished_text}" + spaces + "\n") | |
terminal.flush() | |
try: | |
t = Thread(target=animation) | |
t.start() | |
yield t | |
finally: | |
done = True | |
t.join() | |
def with_loading_animation(running_text: str = "Running", finished_text: str = "Done!"): | |
def wrapper(f): | |
def wrapped(*args, **kwargs): | |
with loading_animation(running_text, finished_text): | |
return f(*args, **kwargs) | |
return wrapped | |
return wrapper | |
# Usage examples | |
if __name__ == "__main__": | |
# As decorator | |
# Custom text | |
@with_loading_animation("Sleeping", "Had a good nap") | |
def test_function(time: int): | |
sleep(time) | |
# Default text | |
@with_loading_animation() | |
def test_function2(time: int): | |
sleep(time) | |
test_function(3) | |
test_function2(3) | |
# With with statement | |
# Custom text | |
with loading_animation("Wallowing in context", "Had a nice little block"): | |
sleep(3) | |
# With default | |
with loading_animation(): | |
sleep(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment