Skip to content

Instantly share code, notes, and snippets.

@furas
Last active June 10, 2021 18:04
Show Gist options
  • Save furas/5eb84b07de69ef9298a971c1eff28126 to your computer and use it in GitHub Desktop.
Save furas/5eb84b07de69ef9298a971c1eff28126 to your computer and use it in GitHub Desktop.
[python] spin animation during long running code
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2021.06.10
# https://stackoverflow.com/questions/67904508/custom-animation-while-python-connects-to-remote-mysql-database
# spinning animation during long running code
import threading
import time
# single char \ has special meaning in string so it needs \\
# or string needs prefix `r` for `raw` string: animation=r'|/-\'
def spinning(delay=0.1, animation='|/-\\'):
global running
running = True
length = len(animation)
index = 0
while running:
print(animation[index], end='\r', flush=True) # it may need flush to send on screen when there is no `\n`
index = (index + 1) % length # modulo `%`
time.sleep(delay)
def connecting():
"""Long running code."""
time.sleep(5)
# --- main ---
#t = threading.Thread( target=spinning, args=(0.05, '-/|\\'))
#t = threading.Thread(target=spinning, kwargs={'delay': 0.05, 'animation': '-/|\\'})
t = threading.Thread(target=spinning)
print('start')
running = True
t.start()
connecting()
running = False
t.join()
print('end')
# to run animation again you have to create `thread` again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment