首页 文章

asyncio事件循环可以在后台运行而不挂起Python解释器吗?

提问于
浏览
18

asyncio的文档提供了两个如何每两秒打印"Hello World"的示例:https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback https://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine

我可以从解释器运行那些,但如果我这样做,我将无法访问解释器 . 是否可以在后台运行asyncio事件循环,以便我可以在解释器中输入命令?

1 回答

  • 36

    您可以在后台线程中运行事件循环:

    >>> import asyncio
    >>> 
    >>> @asyncio.coroutine
    ... def greet_every_two_seconds():
    ...     while True:
    ...         print('Hello World')
    ...         yield from asyncio.sleep(2)
    ... 
    >>> def loop_in_thread(loop):
    ...     asyncio.set_event_loop(loop)
    ...     loop.run_until_complete(greet_every_two_seconds())
    ... 
    >>> 
    >>> loop = asyncio.get_event_loop()
    >>> import threading
    >>> t = threading.Thread(target=loop_in_thread, args=(loop,))
    >>> t.start()
    Hello World
    >>> 
    >>> Hello World
    

    请注意,您必须在 loop 上调用 asyncio.set_event_loop ,否则您将'll get an error saying that the current thread doesn'具有事件循环 .

    如果要与主线程中的事件循环进行交互,则需要坚持loop.call_soon_threadsafe调用 .

    虽然这种方法是在解释器中进行实验的好方法,但在实际程序中,您可能希望所有代码都在事件循环中运行,而不是引入线程 .

相关问题