示例

import asyncio
async def func(id):
    print(id)
    
tasks = []
loop = asyncio.get_event_loop()
for id in range(10):
    tasks.append(func(id))

loop.run_until_complete(tasks)

疑难杂症

其他线程中使用会报错

RuntimeError: There is no current event loop in thread 'LoopThread'.

需要新建一个loop

import asyncio
async def func(id):
    print(id)

tasks = []
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
for id in range(10):
    tasks.append(func(id))

new_loop.run_until_complete(asyncio.wait(tasks))

如果函数内没有await, 会报错

TypeError: An asyncio.Future, a coroutine or an awaitable is required

所以运行前加一个asyncio.wait

如果觉得我的文章对你有用,请随意赞赏