Skip to content

Instantly share code, notes, and snippets.

@akupar
Forked from Jiler01/Loading_animation.py
Last active January 31, 2025 21:15
Show Gist options
  • Save akupar/19ee10dd67a53fa170b42e588b720ad1 to your computer and use it in GitHub Desktop.
Save akupar/19ee10dd67a53fa170b42e588b720ad1 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 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
@contextmanager
def loading_animation(running_text: str = "Running", finished_text: str = "Done!"):
diff = len(running_text) - len(finished_text) + 2
spaces = " " * diff if diff > 0 else ""
done = False
def animation():
for c in cycle(['|', '/', '-', '\\']):
if done:
break
terminal.write(f'\r{running_text} ' + c)
terminal.flush()
sleep(0.1)
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)
@ivanignatiev
Copy link

I forked your solution to display also number of seconds the user is waiting for process to complete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment