# 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.