Skip to content

Instantly share code, notes, and snippets.

@clintval
Created March 20, 2018 23:09
Show Gist options
  • Select an option

  • Save clintval/5f82f5803b85fd6d2e4006ada359ec38 to your computer and use it in GitHub Desktop.

Select an option

Save clintval/5f82f5803b85fd6d2e4006ada359ec38 to your computer and use it in GitHub Desktop.
A non-blocking terminal spinner for Python
import sys
import threading
import time
# Really though just use a library for this:
# https://github.com/ManrajGrover/halo
#
class Spinner:
"""https://stackoverflow.com/a/39504463/3727678"""
busy = False
delay = 0.1
def spinning_cursor(self):
while 1:
for cursor in '◇◈◆':
yield cursor + self.message
def __init__(self, message='', delay=None):
self.message = message
self.spinner_generator = self.spinning_cursor()
if delay and float(delay):
self.delay = delay
def spinner_task(self):
while self.busy:
sys.stdout.write(next(self.spinner_generator))
sys.stdout.flush()
time.sleep(self.delay)
sys.stdout.write('\b' * (len(self.message) + 1))
sys.stdout.flush()
def start(self):
self.busy = True
threading.Thread(target=self.spinner_task).start()
def stop(self):
self.busy = False
time.sleep(self.delay)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment