Skip to content

Instantly share code, notes, and snippets.

@travishen
Created May 5, 2022 11:40
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 travishen/5f190321bcfa531315f56528166c68f8 to your computer and use it in GitHub Desktop.
Save travishen/5f190321bcfa531315f56528166c68f8 to your computer and use it in GitHub Desktop.
Spinner threading
import sys
import threading
class Signal:
stop = False
def spin(signal):
write, flush = sys.stdout.write, sys.stdout.flush # create alias
for char in itertools.cycle('|/-\\'):
msg = char + ' loading ...'
write(msg)
flush()
write('\x08' * len(msg)) # use char \x08 to move cursor back
time.sleep(.1) # control spin rate
if signal.stop:
break
# use space to clear line and move cursor to head
write(' ' * len(msg) + '\x08' * len(msg))
def slow_func():
time.sleep(5) # blocking I/O
return True
signal = Signal()
spinner = threading.Thread(target=spin, args=(signal,))
spinner.start() # start spinner thread
result = slow_func() # main thread blocked here
# slow_func done, trigger spinner thread to stop
signal.stop = True
spinner.join() # wait until finish
print(f'Result: {result}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment