diff --git a/tests/test_timer.py b/tests/test_timer.py index 33de062..e66adc2 100644 --- a/tests/test_timer.py +++ b/tests/test_timer.py @@ -78,3 +78,13 @@ def test_timer_finished(): sp._freeze("") assert re.search(r"\(\d+:\d{2}:\d{2}.\d{2}\)", sp._last_frame) is not None + + +def test_timer_custom_format(): + sp = yaspin(timer="#{}---{}#") + + assert sp.elapsed_time == 0 + + sp._freeze("") + + assert "#0:00:00---0#" in sp._last_frame diff --git a/yaspin/api.py b/yaspin/api.py index 07a847e..b1f2fb6 100644 --- a/yaspin/api.py +++ b/yaspin/api.py @@ -30,7 +30,7 @@ def yaspin(*args: Any, **kwargs: Any) -> Yaspin: of the text string. sigmap (dict, optional): Maps POSIX signals to their respective handlers. - timer (bool, optional): Prints a timer showing the elapsed time. + timer (bool | str, optional): Prints a timer showing the elapsed time. Returns: core.Yaspin: instance of the Yaspin class. diff --git a/yaspin/core.py b/yaspin/core.py index 798b5be..f175093 100644 --- a/yaspin/core.py +++ b/yaspin/core.py @@ -107,7 +107,7 @@ def __init__( # pylint: disable=too-many-arguments reversal: bool = False, side: str = "left", sigmap: Optional[dict[signal.Signals, SignalHandlers]] = None, - timer: bool = False, + timer: Union[bool, str] = False, ) -> None: # Spinner self._spinner = self._set_spinner(spinner) @@ -444,9 +444,11 @@ def _compose_out(self, frame: str, mode: Optional[str] = None) -> str: if self._side == "right": frame, text = text, frame # Timer - if self._timer: + if self._timer is not False: + # TODO the format string should allow showing custom groupings (such as total seconds or HH:MM:SS) + timer_format = self._timer if isinstance(self._timer, str) else " ({}.{:02.0f})" sec, fsec = divmod(round(100 * self.elapsed_time), 100) - text += " ({}.{:02.0f})".format( # pylint: disable=consider-using-f-string + text += timer_format.format( # pylint: disable=consider-using-f-string timedelta(seconds=sec), fsec ) # Mode