【发布时间】:2018-07-13 23:35:18
【问题描述】:
是简单的测试代码和结果。
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(),并期望test() 嵌套的asyncio.sleep(1) 也使用new loop。
与此相反,sleep() 似乎仍然可以访问 main loop 我设置为 None。
我知道我可以在调用run_until_complete() 之前将main loop 重新设置为new loop 和asyncio.set_event_loop(loop),它会正常工作。
但是,我想知道对于asyncio 来说,main loop 必须设置并用于协程是正常的,无论在哪个循环上运行协程。
【问题讨论】:
标签: python python-3.x python-3.5 python-asyncio event-loop