Fix context managers behavior on exceptions.

This commit is contained in:
Florian Bruhin 2015-06-15 06:18:16 +02:00
parent 8dc9f0562a
commit 70699988ed
3 changed files with 21 additions and 13 deletions

View File

@ -230,10 +230,12 @@ def log_time(logger, action='operation'):
action: A description of what's being done. action: A description of what's being done.
""" """
started = datetime.datetime.now() started = datetime.datetime.now()
yield try:
finished = datetime.datetime.now() yield
delta = (finished - started).total_seconds() finally:
logger.debug("{} took {} seconds.".format(action.capitalize(), delta)) finished = datetime.datetime.now()
delta = (finished - started).total_seconds()
logger.debug("{} took {} seconds.".format(action.capitalize(), delta))
def _get_widgets(): def _get_widgets():

View File

@ -159,8 +159,10 @@ def init_log(args):
def disable_qt_msghandler(): def disable_qt_msghandler():
"""Contextmanager which temporarily disables the Qt message handler.""" """Contextmanager which temporarily disables the Qt message handler."""
old_handler = QtCore.qInstallMessageHandler(None) old_handler = QtCore.qInstallMessageHandler(None)
yield try:
QtCore.qInstallMessageHandler(old_handler) yield
finally:
QtCore.qInstallMessageHandler(old_handler)
def _init_handlers(level, color, ram_capacity): def _init_handlers(level, color, ram_capacity):
@ -319,8 +321,10 @@ def hide_qt_warning(pattern, logger='qt'):
log_filter = QtWarningFilter(pattern) log_filter = QtWarningFilter(pattern)
logger_obj = logging.getLogger(logger) logger_obj = logging.getLogger(logger)
logger_obj.addFilter(log_filter) logger_obj.addFilter(log_filter)
yield try:
logger_obj.removeFilter(log_filter) yield
finally:
logger_obj.removeFilter(log_filter)
class QtWarningFilter(logging.Filter): class QtWarningFilter(logging.Filter):

View File

@ -438,11 +438,13 @@ def disabled_excepthook():
"""Run code with the exception hook temporarily disabled.""" """Run code with the exception hook temporarily disabled."""
old_excepthook = sys.excepthook old_excepthook = sys.excepthook
sys.excepthook = sys.__excepthook__ sys.excepthook = sys.__excepthook__
yield try:
# If the code we did run did change sys.excepthook, we leave it yield
# unchanged. Otherwise, we reset it. finally:
if sys.excepthook is sys.__excepthook__: # If the code we did run did change sys.excepthook, we leave it
sys.excepthook = old_excepthook # unchanged. Otherwise, we reset it.
if sys.excepthook is sys.__excepthook__:
sys.excepthook = old_excepthook
class prevent_exceptions: # pylint: disable=invalid-name class prevent_exceptions: # pylint: disable=invalid-name