Skip to content

Instantly share code, notes, and snippets.

@cevaris
Forked from anonymous/spinner.py
Created November 12, 2015 16:45
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save cevaris/79700649f0543584009e to your computer and use it in GitHub Desktop.
Save cevaris/79700649f0543584009e to your computer and use it in GitHub Desktop.
Simple Python CLI Spinner
#!/usr/bin/env python
import itertools
import sys
import time
import threading
class Spinner(object):
spinner_cycle = itertools.cycle(['-', '/', '|', '\\'])
def __init__(self):
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()
def init_spin(self):
while not self.stop_running.is_set():
sys.stdout.write(self.spinner_cycle.next())
sys.stdout.flush()
time.sleep(0.25)
sys.stdout.write('\b')
#!/usr/bin/env python
def do_work():
time.sleep(3)
print 'starting work'
spinner = Spinner()
spinner.start()
do_work()
spinner.stop()
print 'all done!'
@ernstki
Copy link

ernstki commented Oct 17, 2018

Nowadays, there is no .next() method on an itertools.cycle.

Replacing line #25 with this will make this gist work again (in Python 2.7.x and Python 3)

sys.stdout.write(next(self.spinner_cycle))

See also: this SO thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment