sh_cpl/src/cpl/console/spinner_thread.py

50 lines
1.3 KiB
Python
Raw Normal View History

2021-03-05 17:09:12 +01:00
import sys
2021-03-05 15:55:14 +01:00
import threading
import time
2021-03-10 17:04:28 +01:00
from termcolor import colored
from cpl.console.background_color import BackgroundColor
from cpl.console.foreground_color import ForegroundColor
2021-03-05 15:55:14 +01:00
class SpinnerThread(threading.Thread):
2021-03-10 17:04:28 +01:00
def __init__(self, foreground_color: ForegroundColor, background_color: BackgroundColor):
2021-03-05 15:55:14 +01:00
threading.Thread.__init__(self)
self._is_spinning = True
2021-03-10 17:04:28 +01:00
self._foreground_color = foreground_color
self._background_color = background_color
2021-03-05 15:55:14 +01:00
@staticmethod
def _spinner():
while True:
for cursor in '|/-\\':
yield cursor
2021-03-10 17:04:28 +01:00
def _get_color_args(self) -> list[str]:
color_args = []
if self._foreground_color is not None:
color_args.append(str(self._foreground_color.value))
if self._background_color is not None:
color_args.append(str(self._background_color.value))
return color_args
2021-03-05 15:55:14 +01:00
def run(self) -> None:
2021-03-05 17:09:12 +01:00
print('\t', end='')
2021-03-05 15:55:14 +01:00
spinner = self._spinner()
while self._is_spinning:
2021-03-10 17:04:28 +01:00
print(colored(next(spinner), *self._get_color_args()), end='')
2021-03-05 15:55:14 +01:00
time.sleep(0.1)
2021-03-05 17:09:12 +01:00
print('\b', end='')
sys.stdout.flush()
2021-03-05 15:55:14 +01:00
2021-03-10 17:04:28 +01:00
print(colored('done', *self._get_color_args()), end='')
2021-03-05 15:55:14 +01:00
def stop_spinning(self):
self._is_spinning = False
time.sleep(0.1)