Skip to content

Instantly share code, notes, and snippets.

@Jiler01
Forked from rudrathegreat/Loading.py
Last active May 12, 2024 20:33
Show Gist options
  • Save Jiler01/71cca4a314648920f2c130ced8f7329d to your computer and use it in GitHub Desktop.
Save Jiler01/71cca4a314648920f2c130ced8f7329d to your computer and use it in GitHub Desktop.
A Simple Loading Animation Decorator 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
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 ""
def wrapper(f):
def wrapped(*args, **kwargs):
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()
t = Thread(target=animation)
t.start()
result = f(*args, **kwargs)
done = True
t.join()
return result
return wrapped
return wrapper
# Usage examples
if __name__ == "__main__":
# Custom text
@loading_animation("Sleeping", "Had a good nap")
def test_function(time: int):
sleep(time)
# Default text
@loading_animation()
def test_function2(time: int):
sleep(time)
test_function(3)
test_function2(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment