furas

spinning animation during long running code

Jun 10th, 2021 (edited)
479
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
  2. # date: 2021.06.10
  3. # https://stackoverflow.com/questions/67904508/custom-animation-while-python-connects-to-remote-mysql-database
  4.  
  5. # spinning animation during long running code
  6.  
  7. import threading
  8. import time
  9.  
  10. # single char \ has special meaning in string so it needs \\
  11. # or string needs prefix `r` for `raw` string: animation=r'|/-\'
  12. def spinning(delay=0.1, animation='|/-\\'):
  13.     global running
  14.    
  15.     running = True
  16.    
  17.     length = len(animation)
  18.     index = 0
  19.    
  20.     while running:
  21.         print(animation[index], end='\r', flush=True)  # it may need flush to send on screen when there is no `\n`
  22.         index = (index + 1) % length  # modulo `%`
  23.         time.sleep(delay)
  24.  
  25. def connecting():
  26.     """Long running code."""
  27.     time.sleep(5)
  28.        
  29. # --- main ---
  30.  
  31. #t = threading.Thread( target=spinning, args=(0.05, '-/|\\'))
  32. #t = threading.Thread(target=spinning, kwargs={'delay': 0.05, 'animation': '-/|\\'})
  33. t = threading.Thread(target=spinning)
  34.  
  35. print('start')
  36. running = True        
  37. t.start()
  38.  
  39. connecting()
  40.  
  41. running = False
  42. t.join()
  43. print('end')
  44.  
  45. # to run animation again you have to create `thread` again.
RAW Paste Data