Skip to content

Commit

Permalink
fix writing to closed file
Browse files Browse the repository at this point in the history
- fixes #1033
  • Loading branch information
casperdcl committed Sep 18, 2020
1 parent 3f7e8e9 commit d3c07ae
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion tqdm/std.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .utils import _supports_unicode, _screen_shape_wrapper, _range, _unich, \
_term_move_up, _unicode, WeakSet, _basestring, _OrderedDict, \
Comparable, _is_ascii, FormatReplace, disp_len, disp_trim, \
SimpleTextIOWrapper, CallbackIOWrapper
SimpleTextIOWrapper, DisableOnWriteError, CallbackIOWrapper
from ._monitor import TMonitor
# native libraries
from contextlib import contextmanager
Expand Down Expand Up @@ -929,6 +929,8 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True,
file = SimpleTextIOWrapper(
file, encoding=getattr(file, 'encoding', None) or 'utf-8')

file = DisableOnWriteError(file, tqdm_instance=self)

if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True

Expand Down
30 changes: 30 additions & 0 deletions tqdm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,36 @@ def __eq__(self, other):
return self._wrapped == getattr(other, '_wrapped', other)


class DisableOnWriteError(ObjectWrapper):
"""
Disable the given `tqdm_instance` upon `write()` or `flush()` errors.
"""
@staticmethod
def disable_on_exception(tqdm_instance, func, exc):
"""
Quietly set `tqdm_instance.disable=True` if `func` raises `exc`.
"""
@wraps(func)
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc:
tqdm_instance.disable = True
return inner

def __init__(self, wrapped, tqdm_instance):
super(DisableOnWriteError, self).__init__(wrapped)
if hasattr(wrapped, 'write'):
self.wrapper_setattr('write', self.disable_on_exception(
tqdm_instance, wrapped.write, (IOError, OSError)))
if hasattr(wrapped, 'flush'):
self.wrapper_setattr('flush', self.disable_on_exception(
tqdm_instance, wrapped.flush, (IOError, OSError)))

def __eq__(self, other):
return self._wrapped == getattr(other, '_wrapped', other)


class CallbackIOWrapper(ObjectWrapper):
def __init__(self, callback, stream, method="read"):
"""
Expand Down

0 comments on commit d3c07ae

Please sign in to comment.