diff --git a/README.rst b/README.rst index 79a8eff..4cf954b 100644 --- a/README.rst +++ b/README.rst @@ -88,6 +88,16 @@ For actions with an unknown number of steps you can use a spinner. :: # Do some work spinner.next() +Spinners can run in the background, for example, during a long, blocking +call. They will automatically be advanced with a customizable frequency +controlled by the ``frequency`` keyword argument (0.1 seconds by default) +This behvaior is available using the ``with`` statement. :: + + from progress.spinner import Spinner + + with Spinner('Loading ', frequency=0.1): + # Do some work, or make a blocking call + There are 4 predefined spinners: - Spinner diff --git a/progress/__init__.py b/progress/__init__.py index 5107bc0..a9a3d22 100644 --- a/progress/__init__.py +++ b/progress/__init__.py @@ -19,6 +19,7 @@ from math import ceil from sys import stderr from time import time +from threading import Thread, Event __version__ = '1.2' @@ -78,6 +79,24 @@ def iter(self, it): self.next() self.finish() + def _run(self): + frequency = getattr(self, 'frequency', 0.1) + while not self._event.is_set(): + self.next() + self._event.wait(frequency) + + def __enter__(self): + self.start() + self._event = Event() + self._thread = Thread(target=self._run) + self._thread.start() + + def __exit__(self, exc_type, exc_value, exc_tb): + self._event.set() + self._thread.join() + self.finish() + + class Progress(Infinite): def __init__(self, *args, **kwargs): diff --git a/test_progress.py b/test_progress.py index ecb6125..c51c42e 100755 --- a/test_progress.py +++ b/test_progress.py @@ -37,3 +37,7 @@ bar.goto(randint(0, 100)) sleep(0.1) bar.finish() + +with Spinner('ThreadedSpinner '): + sleep(3) +print()