asyncio.run RuntimeError:事件循环已关闭

时间:2020-05-01 13:28:00

标签: python runtime-error python-asyncio roblox event-loop

import robloxapi, asyncio
client = robloxapi.Client(".ROBLOSECURITY Cookie Here") # Removed this for security reasons

async def main():
    user = await client.get_self()

    try:
        role = await user.get_role_in_group(1)
    except robloxapi.utils.errors.NotFound:
        role = None

    if role:    
        print(role.name)
    else:
        print("Not in group")

asyncio.run(main())

此代码引发RuntimeError: Event loop is closed,但我不知道为什么,

我尝试用此替换asyncio.run

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

但是它给了我同样的错误

2 个答案:

答案 0 :(得分:2)

在 Windows 上执行此操作:

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

答案 1 :(得分:1)

我是StackOverflow的新手,我无法发表评论。我会在这里写答案。我在异步处理中遇到了类似的问题。

因此,通过更改Eventloop python正在使用,解决了我遇到的问题。

在低于3.8-的python版本中: -在Windows上使用SelectorEventLoop -ProactorEventLoop在Linux上使用。

(在python 3.8+中,它们都是ProactorEventLoop),因此,如果您安装了python 3.8+,这将无济于事。因为您将在Windows上拥有与WSL相同的eventloop。

如果您的Python版本低于3.8,则可能会有所帮助。

因此您可以尝试手动设置在您使用WSL时也使用ProactorEventLoop

asyncio.set_event_loop(asyncio.ProactorEventLoop())

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

希望这些信息对您有所帮助。