运行 简单异步脚本时出现 ValueError

ValueError when running simple asyncio script

我正在学习 asycio 并尝试 运行 这个脚本我得到这个错误:

ValueError: a coroutine was expected, got <async_generator object mygen at 0x7fa2af959a60>

我在这里错过了什么?

import asyncio

async def mygen(u=10):
     """Yield powers of 2."""
     i = 0
     while i < int(u):
         yield 2 ** i
         i += 1
         await asyncio.sleep(0.1)

asyncio.run(mygen(5))

asyncio.run function expects a coroutine but mygen is an asynchronous generator.

您可以尝试这样的操作:

test.py:

import asyncio


async def mygen(u=10):
    """Yield powers of 2."""
    i = 0
    while i < int(u):
        yield 2**i
        i += 1
        await asyncio.sleep(0.1)


async def main():
    async for i in mygen(5):
        print(i)


if __name__ == "__main__":
    asyncio.run(main())

测试:

$ python test.py 
1
2
4
8
16

参考文献: