【问题标题】:running python application with asyncio async and await使用 asyncio async 和 await 运行 python 应用程序
【发布时间】:2018-09-24 01:39:25
【问题描述】:

我正在尝试在 python 3.5 中使用 asyncio 和关键字 await/async 我对python中的异步编程相当陌生。我的大部分经验都是使用 NodeJS。除了调用我的启动函数来启动程序之外,我似乎做的一切都是正确的。

下面是一些虚构的代码,可以将其淡化到我感到困惑的地方,因为我的代码库相当大并且由几个本地模块组成。

import asyncio

async def get_data():
    foo = await <retrieve some data>
    return foo

async def run():
    await get_data()

run()

但我收到了这个异步异常: runtimeWarning: coroutine 'run' was never awaited

我明白这个错误告诉我什么,但我很困惑我应该如何等待对函数的调用才能运行我的程序。

【问题讨论】:

    标签: asynchronous python-3.5 python-asyncio


    【解决方案1】:

    你应该手动创建事件循环并在其中运行协程,如documentation所示:

    import asyncio
    
    
    async def hello_world():
        print("Hello World!")
    
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(hello_world())
    loop.close()
    

    【讨论】:

    • 这很有意义。我误解了循环的概念。我的代码在主事件循环内,但我需要设置一个异步事件循环。
    • @RileyHughes 明确一点:与 Python 中的 NodeJS 不同,没有任何类型的默认解释器级事件循环。上面代码中的事件循环是 asyncio 模块的一部分:您需要对其进行设置以在其中运行 asyncio 协程。
    猜你喜欢
    • 2022-06-12
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多