python3.8运行时错误: no running event loop

标签 python python-asyncio python-3.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.8运行时错误: no running event loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70875426/

相关文章:

python - 如何使用 Python 3.8 alpha 中引入的赋值表达式重写这个简单的循环?

python - 如何获得不和谐公会的成员(discord.py)?

python - 按最接近 0 的值对 Django 查询集进行排序

python - 查找最近修改的文件并操作输出

python - Pandas DataFrame 按两列分组并添加移动平均列

python - 创建在协程完成时产生协程结果的生成器

python - 为什么 asyncio 的事件循环会抑制 Windows 上的 KeyboardInterrupt?

python - 为什么 RabbitMQ 不在持久队列中持久化消息?

python - Django 休息框架中的异步

python - Django 中的 cached_property 与 Python 的 functools 有什么区别?