gpt4 book ai didi

python - 异常 "There is no current event loop in thread ' MainThread'“在运行新循环时

转载 作者:太空狗 更新时间:2023-10-29 23:57:00 24 4
gpt4 key购买 nike

这是简单的测试代码和结果。

import asyncio

async def test():
await asyncio.sleep(1)

if __name__ == '__main__':

asyncio.set_event_loop(None) # Clear the main loop.
loop = asyncio.new_event_loop() # Create a new loop.
loop.run_until_complete(test()) # Run coroutine over the new loop

Traceback (most recent call last):
File "test_test.py", line 11, in <module>
loop.run_until_complete(test())
File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "test_test.py", line 5, in test
await asyncio.sleep(1)
File "/usr/lib/python3.5/asyncio/tasks.py", line 510, in sleep
loop = events.get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'MainThread'.

我在 new loop 上运行 async def test() 并期望 asyncio.sleep(1) 嵌套在 test() 也使用新循环

与此相反,sleep() 似乎仍然访问main loop 我设置为None

我知道我可以在调用 之前使用 asyncio.set_event_loop(loop)main loop 重新设置为 new loop run_until_complete() 它将无一异常(exception)地工作。

但是,我想知道对于 asyncio 来说,main loop 必须设置并用于协程是正常的,而不管协程在哪个循环上运行。

最佳答案

I want to know it is normal for asyncio that main loop Must be set and is used for coroutines regardless of a loop over which coroutine is run.

这在 Python 3.6 之前是必需的。原因是像asyncio.sleep()这样的函数需要一个事件循环才能使用loop.call_later()来安排唤醒调用来完成 future .

从 Python 3.6(或 3.5.3,其中包含对 the issue 的修复)开始,当 get_event_loop() 从事件循环驱动的协程中调用时,它总是返回事件循环驱动它。因此,您的代码可以正常工作。

在线文档中未提及新行为,但在 the docstring 中提及:

When called from a coroutine or a callback (e.g. scheduled with call_soon or similar API), this function will always return the running event loop.

关于python - 异常 "There is no current event loop in thread ' MainThread'“在运行新循环时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48606389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com