python3.8运行时间错误:没有正在运行的事件循环



我从作者caleb hattingh的一本书中获得了以下代码片段。我尝试运行代码片段,但遇到了这个错误。(实践(

如何解决此问题?

import asyncio
async def f(delay):
await asyncio.sleep(1 / delay)
return delay
loop = asyncio.get_event_loop()
for i in range(10):
loop.create_task(f(i))
print(loop)
pending = asyncio.all_tasks()
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()

您必须将loop作为参数传递给.all_tasks()函数:

pending = asyncio.all_tasks(loop)

输出:

<_UnixSelectorEventLoop running=False closed=False debug=False>
<_GatheringFuture pending>
Results: [8, 5, 2, 9, 6, 3, ZeroDivisionError('division by zero'), 7, 4, 1]

因此,要对您的脚本进行全面更正:

import asyncio
async def f(delay):
if delay:
await asyncio.sleep(1 / delay)
return delay
loop = asyncio.get_event_loop()
for i in range(10):
loop.create_task(f(i))
print(loop)
pending = asyncio.all_tasks(loop)
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()

使用python3.7和更高版本,可以省略事件循环和任务的显式创建和管理。asyncioAPI已经更改了几次,您可以找到涵盖过时语法的教程。以下实现与您的解决方案相对应。

import asyncio
async def f(delay):
await asyncio.sleep(1 / delay)
return delay
async def main():
return await asyncio.gather(*[f(i) for i in range(10)], return_exceptions=True)
print(asyncio.run(main()))

输出

[ZeroDivisionError('division by zero'), 1, 2, 3, 4, 5, 6, 7, 8, 9]

最新更新