运行 python 具有 asyncio async 和 await 的应用程序

running python application with asyncio async and await

我正在尝试将 asyncio 和关键字 await/async 与 python 3.5 一起使用 我对 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

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

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

所示
import asyncio


async def hello_world():
    print("Hello World!")


loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()