Python asyncio._get_running_loop() Examples

The following are 11 code examples of asyncio._get_running_loop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: utils.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_main(main):
    """Main entrypoint for asyncio tasks.

    This differs from `asyncio.run` in one key way - the main task is cancelled
    *first*, then any outstanding tasks are cancelled (and logged, remaining
    tasks are indicative of bugs/failures).
    """
    if asyncio._get_running_loop() is not None:
        raise RuntimeError("Cannot be called from inside a running event loop")

    main_task = None
    loop = asyncio.new_event_loop()
    try:
        asyncio.set_event_loop(loop)
        main_task = loop.create_task(main)
        return loop.run_until_complete(main_task)
    finally:
        try:
            if main_task is not None:
                loop.run_until_complete(cancel_task(main_task))
            _cancel_all_tasks(loop)
            loop.run_until_complete(loop.shutdown_asyncgens())
        finally:
            asyncio.set_event_loop(None)
            loop.close() 
Example #2
Source File: test_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_get_event_loop_returns_running_loop(self):
        class Policy(asyncio.DefaultEventLoopPolicy):
            def get_event_loop(self):
                raise NotImplementedError

        loop = None

        old_policy = asyncio.get_event_loop_policy()
        try:
            asyncio.set_event_loop_policy(Policy())
            loop = asyncio.new_event_loop()
            self.assertIs(asyncio._get_running_loop(), None)

            async def func():
                self.assertIs(asyncio.get_event_loop(), loop)
                self.assertIs(asyncio._get_running_loop(), loop)

            loop.run_until_complete(func())
        finally:
            asyncio.set_event_loop_policy(old_policy)
            if loop is not None:
                loop.close()

        self.assertIs(asyncio._get_running_loop(), None) 
Example #3
Source File: asyncio_compat.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def get_running_loop():
    """Gets the currently running event loop

    Uses asyncio.get_running_loop() if available (Python 3.7+) or a backported
    version of the same function in 3.5/3.6.
    """
    try:
        loop = asyncio.get_running_loop()
    except AttributeError:
        loop = asyncio._get_running_loop()
        if loop is None:
            raise RuntimeError("no running event loop")
    return loop 
Example #4
Source File: asyncio_compat.py    From azure-iot-sdk-python-preview with MIT License 5 votes vote down vote up
def get_running_loop():
    """Gets the currently running event loop

    Uses asyncio.get_running_loop() if available (Python 3.7+) or a backported
    version of the same function in 3.5/3.6.
    """
    try:
        loop = asyncio.get_running_loop()
    except AttributeError:
        loop = asyncio._get_running_loop()
        if loop is None:
            raise RuntimeError("no running event loop")
    return loop 
Example #5
Source File: async_utils.py    From gd.py with MIT License 5 votes vote down vote up
def acquire_loop(running: bool = False) -> asyncio.AbstractEventLoop:
    """Gracefully acquire a loop.

    The function tries to get an event loop via :func:`asyncio.get_event_loop`.
    On fail, returns a new loop using :func:`asyncio.new_event_loop`.

    Parameters
    ----------
    running: :class:`bool`
        Indicates if the function should get a loop that is already running.
    """
    try:
        loop = asyncio._get_running_loop()

    except Exception:  # an error might occur actually
        loop = None

    if running and loop is not None:
        return loop

    else:
        try:
            loop = asyncio.get_event_loop()

            if loop.is_running() and not running:
                # loop is running while we have to get the non-running one,
                # let us raise an error to go into <except> clause.
                raise ValueError("Current event loop is already running.")

        except Exception:
            loop = asyncio.new_event_loop()

    return loop 
Example #6
Source File: aiocontextvarsfix.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def _get_running_loop():
            return _running_loop._loop 
Example #7
Source File: aiocontextvarsfix.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def _get_event_loop():
            current_loop = _get_running_loop()
            if current_loop is not None:
                return current_loop
            return asyncio.events.get_event_loop_policy().get_event_loop() 
Example #8
Source File: compatibility.py    From pysoa with Apache License 2.0 5 votes vote down vote up
def _get_running_loop():
                return _running_loop._loop 
Example #9
Source File: compatibility.py    From pysoa with Apache License 2.0 5 votes vote down vote up
def _get_event_loop():
                current_loop = _get_running_loop()
                if current_loop is not None:
                    return current_loop
                return asyncio.events.get_event_loop_policy().get_event_loop() 
Example #10
Source File: api.py    From tqsdk-python with Apache License 2.0 5 votes vote down vote up
def close(self) -> None:
        """
        关闭天勤接口实例并释放相应资源

        Example::

            # m1901开多3手
            from tqsdk import TqApi
            from contextlib import closing

            with closing(TqApi()) as api:
                api.insert_order(symbol="DCE.m1901", direction="BUY", offset="OPEN", volume=3)
        """
        if self._loop.is_closed():
            return
        if self._loop.is_running():
            raise Exception("不能在协程中调用 close, 如需关闭 api 实例需在 wait_update 返回后再关闭")
        elif asyncio._get_running_loop():
            raise Exception(
                "TqSdk 使用了 python3 的原生协程和异步通讯库 asyncio,您所使用的 IDE 不支持 asyncio, 请使用 pycharm 或其它支持 asyncio 的 IDE")

        # 总会发送 serial_extra_array 数据,由 TqWebHelper 处理
        for _, serial in self._serials.items():
            self._process_serial_extra_array(serial)
        self._run_until_idle()  # 由于有的处于 ready 状态 task 可能需要报撤单, 因此一直运行到没有 ready 状态的 task
        for task in self._tasks:
            task.cancel()
        while self._tasks:  # 等待 task 执行完成
            self._run_once()
        self._loop.run_until_complete(self._loop.shutdown_asyncgens())
        self._loop.close()
        _clear_logs()  # 清除过期日志文件 
Example #11
Source File: __init__.py    From Appdaemon-Test-Framework with MIT License 5 votes vote down vote up
def sync_wrapper(coro):
    def inner_sync_wrapper(self, *args, **kwargs):
        start_new_loop = None
        # try to get the running loop
        # `get_running_loop()` is new in Python 3.7, fall back on privateinternal for 3.6
        try:
            get_running_loop = asyncio.get_running_loop
        except AttributeError:
            get_running_loop = asyncio._get_running_loop

        # If there is no running loop we will need to start a new one and run it to completion
        try:
            if get_running_loop():
                start_new_loop = False
            else:
                start_new_loop = True
        except RuntimeError:
            start_new_loop = True

        if start_new_loop is True:
            f = asyncio.ensure_future(coro(self, *args, **kwargs))
            asyncio.get_event_loop().run_until_complete(f)
            f = f.result()
        else:
            # don't use create_task. It's python3.7 only
            f = asyncio.ensure_future(coro(self, *args, **kwargs))

        return f

    return inner_sync_wrapper

# Monkey patch in our sync_wrapper