Created
May 5, 2022 11:40
-
-
Save travishen/5f190321bcfa531315f56528166c68f8 to your computer and use it in GitHub Desktop.
Spinner threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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