Skip to content

Commit

Permalink
tidy into taskbar submod
Browse files Browse the repository at this point in the history
  • Loading branch information
casperdcl committed Feb 17, 2021
1 parent 7bd9482 commit 662237f
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 53 deletions.
52 changes: 8 additions & 44 deletions tqdm/std.py
Expand Up @@ -19,7 +19,6 @@
from weakref import WeakSet

from ._monitor import TMonitor
from .platform_specific import MetaReporter
from .utils import (
CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace,
SimpleTextIOWrapper, _basestring, _is_ascii, _range, _screen_shape_wrapper,
Expand Down Expand Up @@ -957,7 +956,6 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
-------
out : decorated iterator.
"""
self._entered=0
if write_bytes is None:
write_bytes = file is None and sys.version_info < (3,)

Expand Down Expand Up @@ -1076,7 +1074,6 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
self.postfix = None
self.colour = colour
self._time = time
self.platform_specific_reporter = None
if postfix:
try:
self.set_postfix(refresh=False, **postfix)
Expand Down Expand Up @@ -1122,33 +1119,18 @@ def __len__(self):
else getattr(self, "total", None))

def __enter__(self):
if not self._entered:
self.platform_specific_reporter=MetaReporter(self.total, self.unit).__enter__()
self._entered+=1
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
if self._entered:
if self.platform_specific_reporter:
if exc_traceback:
import traceback
self.platform_specific_reporter.fail("".join(traceback.format_exception(exc_type, exc_value, exc_traceback, limit=1)))
elif self.total and self.n < self.total:
self.platform_specific_reporter.fail("The iteration not reached its finishing amount, though no exception has been thrown.")
self.platform_specific_reporter.__exit__(exc_type, exc_value, exc_traceback)
self.platform_specific_reporter = None
try:
self.close()
except AttributeError:
# maybe eager thread cleanup upon external error
if (exc_type, exc_value, traceback) == (None, None, None):
raise
warn("AttributeError ignored", TqdmWarning, stacklevel=2)
self._entered-=1
return False
def __exit__(self, exc_type, exc_value, traceback):
try:
self.close()
except AttributeError:
# maybe eager thread cleanup upon external error
if (exc_type, exc_value, traceback) == (None, None, None):
raise
warn("AttributeError ignored", TqdmWarning, stacklevel=2)

def __del__(self):
self.__exit__(None, None, None)
self.close()

def __str__(self):
Expand All @@ -1163,8 +1145,6 @@ def __hash__(self):

def __iter__(self):
"""Backward-compatibility to use: for x in tqdm(iterable)"""
if not self._entered and self.iterable:
self.__enter__()

# Inlining instance variables as locals (speed optimisation)
iterable = self.iterable
Expand Down Expand Up @@ -1197,10 +1177,6 @@ def __iter__(self):
last_print_t = self.last_print_t
finally:
self.n = n
if self.platform_specific_reporter:
self.platform_specific_reporter.success()
self.platform_specific_reporter.__exit__(None, None, None)
self.platform_specific_reporter = None
self.close()

def update(self, n=1):
Expand Down Expand Up @@ -1277,9 +1253,6 @@ def close(self):
# Prevent multiple closures
self.disable = True

if self.platform_specific_reporter:
self.platform_specific_reporter.clear()

# decrement instance pos and remove from internal set
pos = abs(self.pos)
self._decr_instances(self)
Expand All @@ -1306,8 +1279,6 @@ def fp_write(s):
# stats for overall rate (no weighted average)
self._ema_dt = lambda: None
self.display(pos=0)
if self.platform_specific_reporter:
self.platform_specific_reporter.clear()
fp_write('\n')
else:
# clear previous display
Expand Down Expand Up @@ -1500,13 +1471,6 @@ def display(self, msg=None, pos=None):

if pos:
self.moveto(pos)

if self.platform_specific_reporter:
self.platform_specific_reporter.prefix(self.desc)
self.platform_specific_reporter.postfix(self.postfix)
#self.platform_specific_reporter.message(msg)
self.platform_specific_reporter.progress(self.n, self.avg_time)

self.sp(self.__str__() if msg is None else msg)
if pos:
self.moveto(-pos)
Expand Down
File renamed without changes.
File renamed without changes.
6 changes: 6 additions & 0 deletions tqdm/taskbar/__init__.py
@@ -0,0 +1,6 @@
from __future__ import division, absolute_import
from .taskbar import tqdm, trange
from .meta_reporter import MetaReporter

__author__ = {"github.com/": ["KOLANICH", "casperdcl"]}
__all__ = ["MetaReporter", "tqdm", "trange"]
@@ -1,8 +1,8 @@
__all__=("MetaReporter",)
import sys
import importlib
from functools import wraps
from .PlatformSpecificProgressReporter import PlatformSpecificProgressReporter
__all__ = ["MetaReporter"]

systemToReporterMapping={
"win32": ("windows_taskbar_extensions", ),
Expand All @@ -25,44 +25,44 @@ def __init__(self, *args, **kwargs):
self.reporters=[]
for cls in reporterClassesToUse:
self.reportersCandidates.append(cls(*args, **kwargs))

@wraps(PlatformSpecificProgressReporter.progress)
def progress(self, *args, **kwargs):
for rep in self.reporters:
rep.progress(*args, **kwargs)

def fail(self, reason:str=None):
for rep in self.reporters:
rep.fail(reason)

def success(self):
for rep in self.reporters:
rep.success()

def prefix(self, prefix:str):
for rep in self.reporters:
rep.prefix(prefix)

def message(self, message:str):
for rep in self.reporters:
rep.message(message)

def postfix(self, postfix:str):
for rep in self.reporters:
rep.postfix(postfix)

def __enter__(self):
for rep in self.reportersCandidates:
#try:
self.reporters.append(rep.__enter__())
#except:
# pass
return self

def __exit__(self, exception_type, exception_value, traceback):
for rep in self.reporters:
rep.__exit__(exception_type, exception_value, traceback)

def clear(self):
for rep in self.reporters:
rep.clear()
94 changes: 94 additions & 0 deletions tqdm/taskbar/taskbar.py
@@ -0,0 +1,94 @@
"""
Cross-platform progress display in the taskbar
"""
from __future__ import division, absolute_import
from .meta_reporter import MetaReporter
from tqdm.std import tqdm as std_tqdm

__author__ = {"github.com/": ["KOLANICH", "casperdcl"]}
__all__ = ['tqdm', 'trange']


class tqdm(std_tqdm):
def __init__(**kwargs):
"""
Same as tqdm.tqdm
"""
self._entered=0
self.platform_specific_reporter = None
super(tqdm, self).__init__(**kwargs)

def __enter__(self):
if not self._entered:
self.platform_specific_reporter=MetaReporter(self.total, self.unit).__enter__()
self._entered+=1
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
if self._entered:
if self.platform_specific_reporter:
if exc_traceback:
import traceback
self.platform_specific_reporter.fail("".join(traceback.format_exception(exc_type, exc_value, exc_traceback, limit=1)))
elif self.total and self.n < self.total:
self.platform_specific_reporter.fail("The iteration not reached its finishing amount, though no exception has been thrown.")
self.platform_specific_reporter.__exit__(exc_type, exc_value, exc_traceback)
self.platform_specific_reporter = None
super(tqdm, self).__exit__(exc_type, exc_value, exc_traceback)
self._entered-=1
return False

def __del__(self):
self.__exit__(None, None, None)
super(tqdm, self).__del__()

def __iter__(self):
"""Backward-compatibility to use: for x in tqdm(iterable)"""
if not self._entered and self.iterable:
self.__enter__()

for obj in super(tqdm, self):
yield obj

if self.platform_specific_reporter:
self.platform_specific_reporter.success()
self.platform_specific_reporter.__exit__(None, None, None)
self.platform_specific_reporter = None

def close(self):
"""Cleanup and (if leave=False) close the progressbar."""
if self.disable:
return

if self.platform_specific_reporter:
self.platform_specific_reporter.clear()

super(tqdm, self).close()

def display(self, msg=None, pos=None):
"""
Use `self.sp` to display `msg` in the specified `pos`.
Consider overloading this function when inheriting to use e.g.:
`self.some_frontend(**self.format_dict)` instead of `self.sp`.
Parameters
----------
msg : str, optional. What to display (default: `repr(self)`).
pos : int, optional. Position to `moveto`
(default: `abs(self.pos)`).
"""
super(tqdm, self).display(self, msg=msg, pos=pos)
if self.platform_specific_reporter:
self.platform_specific_reporter.prefix(self.desc)
self.platform_specific_reporter.postfix(self.postfix)
#self.platform_specific_reporter.message(msg)
self.platform_specific_reporter.progress(self.n, self.avg_time)


def trange(*args, **kwargs):
"""
A shortcut for tqdm(xrange(*args), **kwargs).
On Python3+ range is used instead of xrange.
"""
return tqdm(_range(*args), **kwargs)
File renamed without changes.

0 comments on commit 662237f

Please sign in to comment.