Skip to content

Instantly share code, notes, and snippets.

@Ezbob
Created January 16, 2017 21:45
Show Gist options
  • Save Ezbob/eba027009463dbe4f2ed3b6792443416 to your computer and use it in GitHub Desktop.
Save Ezbob/eba027009463dbe4f2ed3b6792443416 to your computer and use it in GitHub Desktop.
Like my head, this also keeps spinning..
def spin_it(message, frames=('|', '\\', '-', '/'), delay_scale=1):
"""Decorator for printing a message and then start the spinner"""
def inner(function):
def do_function(*args, **kwargs):
sys.stdout.write(message)
spinner = Spinner(frames=frames, delay=delay_scale)
spinner.start()
with io.StringIO() as strout:
with contextlib.redirect_stdout(strout):
output = function(*args, **kwargs)
out = strout.getvalue()
spinner.stop()
sys.stdout.write('\n')
sys.stdout.write(out)
return output
return do_function
return inner
class Spinner:
"""Super simple CLI spinner"""
def __init__(self, frames=('|', '\\', '-', '/'), delay=1, stream=None):
self.frames = it.cycle(frames)
self.number_of_frames = len(frames)
self.delay = delay
self.stream = sys.stdout if stream is None else stream
self.is_running = True
self.thread = None
def start(self):
def do_it():
while self.is_running:
self.stream.write(next(self.frames))
self.stream.flush()
time.sleep(1 / self.number_of_frames * self.delay)
self.stream.write('\b')
self.thread = threading.Thread(target=do_it)
self.thread.start()
def stop(self):
self.is_running = False
self.thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment