Executes a given coroutine and optionally catches exceptions, returning
    them as value. This function is intended to be used internally.

def safe_run(coro, return_exceptions=False):
    """
    Executes a given coroutine and optionally catches exceptions, returning
    them as value. This function is intended to be used internally.
    """
    try:
        result = yield from coro
    except Exception as err:
        if return_exceptions:
            result = err
        else:
            raise err
    return result