2017-08-09 70 views
6

當試圖運行在文檔中給出的ASYNCIO的hello world代碼示例:ASYNCIO事件環路閉合

import asyncio 

async def hello_world(): 
    print("Hello World!") 

loop = asyncio.get_event_loop() 
# Blocking call which returns when the hello_world() coroutine is done 
loop.run_until_complete(hello_world()) 
loop.close() 

我得到的錯誤:

RuntimeError: Event loop is closed 

我使用Python 3.5.3。

回答

12

您已經呼籲loop.close()您運行的代碼,樣片之前,對全球事件循環:

>>> import asyncio 
>>> asyncio.get_event_loop().close() 
>>> asyncio.get_event_loop().is_closed() 
True 
>>> asyncio.get_event_loop().run_until_complete(asyncio.sleep(1)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/.../lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete 
    self._check_closed() 
    File "/.../lib/python3.6/asyncio/base_events.py", line 357, in _check_closed 
    raise RuntimeError('Event loop is closed') 
RuntimeError: Event loop is closed 

你需要創建一個循環:

loop = asyncio.new_event_loop() 

你可以設置爲新的全局循環:

asyncio.set_event_loop(asyncio.new_event_loop()) 

,然後再次使用asyncio.get_event_loop()

或者,只要重新啓動您的Python解釋器,第一次嘗試獲取全局事件循環時,您會得到一個全新的新的未關閉的事件循環。