Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an asynchronous progress spinner in Python?

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?

like image 742
meteor23 Avatar asked Sep 15 '25 03:09

meteor23


1 Answers

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()
like image 114
Stefan Falk Avatar answered Sep 17 '25 17:09

Stefan Falk