【问题标题】:python3.8 RuntimeError: no running event looppython3.8 RuntimeError:没有正在运行的事件循环
【发布时间】:2022-01-27 17:24:56
【问题描述】:

我从作者 caleb hattingh 的书中获取了以下代码 sn-p。我尝试运行代码 sn-p 并遇到此错误。(练习)

我该如何解决这个问题?

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()

【问题讨论】:

标签: python python-asyncio python-3.8


【解决方案1】:

您必须将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()

【讨论】:

    【解决方案2】:

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

    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]
    

    【讨论】:

    • 嗨,非常有用的解决方案。顺便说一句,如果我们想使用asyncio.create_task() 手动创建任务,仍然会出现此错误,是否有任何解决方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多