This is the code for the progress spinner:
import sys
import time
def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor
spinner = spinning_cursor()
for _ in range(50):
    sys.stdout.write(spinner.next())
    sys.stdout.flush()
    time.sleep(10)
    sys.stdout.write('\b')
Output
python2.7 test.py
|
It is spinning very slowly since the loop sleeps for 10 seconds...
How do I keep rotating the spinner while the process is sleeping?
You'll have to create a separate thread. The example below roughly shows how this can be done. However, this is just a simple example.
import sys
import time
import threading
class SpinnerThread(threading.Thread):
    def __init__(self):
        super().__init__(target=self._spin)
        self._stopevent = threading.Event()
    def stop(self):
        self._stopevent.set()
    def _spin(self):
        while not self._stopevent.isSet():
            for t in '|/-\\':
                sys.stdout.write(t)
                sys.stdout.flush()
                time.sleep(0.1)
                sys.stdout.write('\b')
def long_task():
    for i in range(10):
        time.sleep(1)
        print('Tick {:d}'.format(i))
def main():
    task = threading.Thread(target=long_task)
    task.start()
    spinner_thread = SpinnerThread()
    spinner_thread.start()
    task.join()
    spinner_thread.stop()
if __name__ == '__main__':
    main()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With