From ae4709b0d4da5055349a1d29108e95fd4dab7fba Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Wed, 10 Mar 2021 20:34:00 +0100 Subject: [PATCH] Improved spinner --- src/cpl/console/console.py | 2 +- src/cpl/console/spinner_thread.py | 22 ++++++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/cpl/console/console.py b/src/cpl/console/console.py index 6d065170..dba6f319 100644 --- a/src/cpl/console/console.py +++ b/src/cpl/console/console.py @@ -265,7 +265,7 @@ class Console: cls.write_line(message) cls.set_hold_back(True) - spinner = SpinnerThread(spinner_foreground_color, spinner_background_color) + spinner = SpinnerThread(len(message), spinner_foreground_color, spinner_background_color) spinner.start() return_value = call(*args) spinner.stop_spinning() diff --git a/src/cpl/console/spinner_thread.py b/src/cpl/console/spinner_thread.py index 6d4be6dd..ff13eb9e 100644 --- a/src/cpl/console/spinner_thread.py +++ b/src/cpl/console/spinner_thread.py @@ -1,3 +1,4 @@ +import os import sys import threading import time @@ -10,13 +11,15 @@ from cpl.console.foreground_color import ForegroundColor class SpinnerThread(threading.Thread): - def __init__(self, foreground_color: ForegroundColor, background_color: BackgroundColor): + def __init__(self, msg_len: int, foreground_color: ForegroundColor, background_color: BackgroundColor): threading.Thread.__init__(self) - self._is_spinning = True + self._msg_len = msg_len self._foreground_color = foreground_color self._background_color = background_color + self._is_spinning = True + @staticmethod def _spinner(): while True: @@ -34,15 +37,22 @@ class SpinnerThread(threading.Thread): return color_args def run(self) -> None: - print('\t', end='') + rows, columns = os.popen('stty size', 'r').read().split() + end_msg = 'done' + columns = int(columns) - self._msg_len - len(end_msg) + print(f'{"" : >{columns}}', end='') spinner = self._spinner() while self._is_spinning: - print(colored(next(spinner), *self._get_color_args()), end='') + print(colored(f'{next(spinner): >{len(end_msg)}}', *self._get_color_args()), end='') time.sleep(0.1) - print('\b', end='') + back = '' + for i in range(0, len(end_msg)): + back += '\b' + + print(back, end='') sys.stdout.flush() - print(colored('done', *self._get_color_args()), end='') + print(colored(end_msg, *self._get_color_args()), end='') def stop_spinning(self): self._is_spinning = False