Source code for pylab_ml.common.spinner

"""
This script contains a spinner class that can be used to display a spinning cursor in the console while a long-running task is being executed. 
The spinner class uses a separate thread to update the cursor while the main thread is busy with the task.


:Date: |today|
:Author: Zlin526F

"""

import sys
import time
import threading

__author__ = "Zlin526F"
__copyright__ = "Copyright 2021, Lab"
__credits__ = ["Zlin526F"]
__email__ = "Zlin526F@github"


[docs] class spinner: """ A class to display a spinning cursor in the console while a long-running task is being executed. """ busy = False delay = 0.1
[docs] @staticmethod def spinning_cursor(): """ A generator that yields a spinning cursor character. """ while 1: for cursor in "|/-\\": yield cursor
[docs] def __init__(self, delay=None): self.spinner_generator = self.spinning_cursor() if delay and float(delay): self.delay = delay
[docs] def spinner_task(self): """ The task that updates the spinner in the console. """ while self.busy: sys.stdout.write(next(self.spinner_generator)) sys.stdout.flush() time.sleep(self.delay) sys.stdout.write("\b") # \b = backspace sys.stdout.flush()
def __enter__(self): """ Start the spinner when entering the context. """ self.busy = True threading.Thread(target=self.spinner_task).start() def __exit__(self, exception, value, tb): """ Stop the spinner when exiting the context. """ self.busy = False time.sleep(self.delay) if exception is not None: return False