1""" 2Sebastian Raschka 2014-2017 3Python Progress Indicator Utility 4 5Author: Sebastian Raschka <sebastianraschka.com> 6License: BSD 3 clause 7 8Contributors: https://github.com/rasbt/pyprind/graphs/contributors 9Code Repository: https://github.com/rasbt/pyprind 10PyPI: https://pypi.python.org/pypi/PyPrind 11""" 12 13from pyprind.prog_class import Prog 14import time 15 16 17class ProgPercent(Prog): 18 """ 19 Initializes a progress bar object that allows visuzalization 20 of an iterational computation in the standard output screen. 21 22 Parameters 23 ---------- 24 iterations : `int` 25 Number of iterations for the iterative computation. 26 track_time : `bool` (default: `True`) 27 Prints elapsed time when loop has finished. 28 stream : `int` (default: 2). 29 Setting the output stream. 30 Takes `1` for stdout, `2` for stderr, or a custom stream object 31 title : `str` (default: `''`). 32 Setting a title for the percentage indicator. 33 monitor : `bool` (default: `False`) 34 Monitors CPU and memory usage if `True` (requires `psutil` package). 35 update_interval : float or int (default: `None`) 36 The update_interval in seconds controls how often the progress 37 is flushed to the screen. 38 Automatic mode if `update_interval=None`. 39 40 """ 41 def __init__(self, iterations, track_time=True, 42 stream=2, title='', monitor=False, update_interval=None): 43 Prog.__init__(self, iterations, track_time, stream, 44 title, monitor, update_interval) 45 self.last_progress = 0 46 self._print() 47 if monitor: 48 try: 49 self.process.cpu_percent() 50 self.process.memory_percent() 51 except AttributeError: # old version of psutil 52 self.process.get_cpu_percent() 53 self.process.get_memory_percent() 54 55 def _cache_percent_indicator(self, last_progress): 56 self._cached_output += '[%3d %%]' % (last_progress) 57 58 def _print(self, force_flush=False): 59 """ Prints formatted percentage and tracked time to the screen.""" 60 self._stream_flush() 61 next_perc = self._calc_percent() 62 if self.update_interval: 63 do_update = time.time() - self.last_time >= self.update_interval 64 elif force_flush: 65 do_update = True 66 else: 67 do_update = next_perc > self.last_progress 68 69 if do_update and self.active: 70 self.last_progress = next_perc 71 self._cache_percent_indicator(self.last_progress) 72 if self.track: 73 self._cached_output += ' Time elapsed: ' + \ 74 self._get_time(self._elapsed()) 75 self._cache_eta() 76 if self.item_id: 77 self._cache_item_id() 78 self._stream_out('\r%s' % self._cached_output) 79 self._stream_flush() 80 self._cached_output = '' 81