Skip to content

Instantly share code, notes, and snippets.

@bhumpert
Created March 21, 2018 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhumpert/10390b6db3c4000e3c8ef9f74e87a27c to your computer and use it in GitHub Desktop.
Save bhumpert/10390b6db3c4000e3c8ef9f74e87a27c to your computer and use it in GitHub Desktop.
Quick CLI animation context manager
import threading
import time
import sys
from itertools import cycle
class Animated():
def __init__(self, anim="|/-\\"):
self.anim = anim
self.run_lock = threading.Lock()
self.thread = threading.Thread(target=self.loop, name='AnimatedThread')
def __enter__(self):
self.start()
def __exit__(self, *e):
self.stop()
def start(self):
self.thread.start()
def stop(self):
self.run_lock.acquire(blocking=True)
self.thread.join()
self.run_lock.release()
def loop(self):
sys.stdout.write(self.anim[0])
for a in cycle(self.anim):
keep_running = self.run_lock.acquire(blocking=False)
if not keep_running: break
try: # overengineered since subthread exceptions ruin the program anyways
sys.stdout.write('\r' + a)
finally:
sys.stdout.write('\r')
self.run_lock.release()
time.sleep(.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment