Skip to content

Instantly share code, notes, and snippets.

@ernstki
Forked from cevaris/spinner.py
Created October 17, 2018 20:35
Show Gist options
  • Save ernstki/149cd53c34a437c2471d87d8dca15654 to your computer and use it in GitHub Desktop.
Save ernstki/149cd53c34a437c2471d87d8dca15654 to your computer and use it in GitHub Desktop.
Simple Python CLI Spinner
#!/usr/bin/env python
# source: https://gist.github.com/cevaris/79700649f0543584009e
# updated to allow an arbitrary message to be displayed in front of the spinner
import itertools
import sys
import time
import threading
class Spinner(object):
msg = ''
spinner_cycle = itertools.cycle(['-', '/', '|', '\\'])
def __init__(self, msg=None):
if msg is not None:
self.msg = msg
self.stop_running = threading.Event()
self.spin_thread = threading.Thread(target=self.init_spin)
def start(self):
self.spin_thread.start()
def stop(self):
self.stop_running.set()
self.spin_thread.join()
sys.stdout.write("\n")
def init_spin(self):
while not self.stop_running.is_set():
sys.stdout.write(self.msg)
sys.stdout.write(next(self.spinner_cycle))
sys.stdout.flush()
time.sleep(0.25)
sys.stdout.write("\b" * (len(self.msg) + 1))
#!/usr/bin/env python
def do_work():
time.sleep(3)
print 'starting work'
spinner = Spinner()
spinner.start()
do_work()
spinner.stop()
print 'all done!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment