mitogen/econtext/utils.py

49 lines
1.3 KiB
Python
Raw Normal View History

2016-08-13 23:16:17 +00:00
"""
A random assortment of utility functions useful on masters and slaves.
"""
2016-08-10 23:06:03 +00:00
import logging
import econtext
2016-08-11 01:39:29 +00:00
import econtext.core
2016-08-10 23:44:18 +00:00
import econtext.master
2016-08-10 23:06:03 +00:00
def log_to_file(path, level=logging.DEBUG):
2016-08-13 23:16:17 +00:00
"""Install a new :py:class:`logging.Handler` writing applications logs to
the filesystem. Useful when debugging slave IO problems."""
2016-08-10 23:06:03 +00:00
log = logging.getLogger('')
fp = open(path, 'w', 1)
2016-08-11 01:39:29 +00:00
econtext.core.set_cloexec(fp.fileno())
2016-08-10 23:06:03 +00:00
log.setLevel(level)
log.handlers.insert(0, logging.StreamHandler(fp))
2016-08-10 21:13:57 +00:00
def run_with_broker(func, *args, **kwargs):
2016-08-13 23:16:17 +00:00
"""Arrange for `func(broker, *args, **kwargs)` to run with a temporary
:py:class:`econtext.master.Broker`, ensuring the broker is correctly
shut down during normal or exceptional return."""
2016-08-10 23:44:18 +00:00
broker = econtext.master.Broker()
2016-08-10 21:13:57 +00:00
try:
return func(broker, *args, **kwargs)
finally:
2016-08-11 17:15:53 +00:00
broker.shutdown()
broker.wait()
2016-08-10 21:13:57 +00:00
def with_broker(func):
2016-08-13 23:16:17 +00:00
"""Decorator version of :py:func:`run_with_broker`. Example:
.. code-block:: python
@with_broker
def do_stuff(broker, arg):
pass
do_stuff(blah, 123)
"""
def wrapper(*args, **kwargs):
2016-08-10 21:13:57 +00:00
return run_with_broker(*args, **kwargs)
wrapper.func_name = func.func_name
return wrapper