python3开启mainloop线程_python – 异常“在新循环上运行时,线程’MainThread’中没有当前事件循环...

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

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

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'.

我在新循环上运行异步def测试(),并期望由test()嵌套的asyncio.sleep(1)也使用新循环.

与此相反,sleep()似乎仍然可以访问我设置为None的主循环.

我知道在调用run_until_complete()之前我可以使用asyncio.set_event_loop(循环)将主循环重新设置为新循环,并且它将无异常地工作.

但是,我想知道asyncio是正常的,主循环必须设置并用于协同程序,而不管运行协同程序的循环.

解决方法:

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()来安排唤醒调用以完成未来.

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

An exception to this rule happens when get_event_loop() is called from a running future/coroutine, in which case it will return the current loop running that future/coroutine.

标签:python,python-3-x,python-asyncio,python-3-5,event-loop