【问题标题】:I need to include all my function in eventloop?我需要在事件循环中包含我的所有功能吗?
【发布时间】:2017-06-16 03:57:39
【问题描述】:

如果我有一个事件循环和异步函数:

# asyncio_coroutine_forever.py


import asyncio

async def hello_world():
    print('Hello World')
    await good_evening()


async def good_evening():
    print('Good Evening')


loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(hello_world())
    loop.run_forever()
finally:
    print('closing event loop')
    loop.close()

函数 hellp_world,由 eventloop 调用。第二个函数good_evening,是否在同一个eventloop中?

我必须在循环中包含第二个函数还是只包含第一个函数? 如果我使用示例,第二个使用循环并切换上下文?

【问题讨论】:

    标签: python async-await python-asyncio


    【解决方案1】:
    1. 是的,run_until_complete 将在未来执行您的 hello_world 直到它返回或失败(它还会在进程中阻塞您的线程)。

    2. 您不必包含第二个函数,除非您想自行安排它。

    run_until_complete 将运行一个 future 直到它完成,但它也会导致事件循环运行,所以如果你安排一个 future,它将在函数传递给 run_util_complete 之前运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 2015-10-06
      • 1970-01-01
      • 2014-10-17
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多