我有一些asyncio的代码,在Python解释器(CPython 3.6.2)中可以正常运行。现在,我想在带有IPython内核的Jupyter Notebook中运行它。
我可以使用下面的命令来运行:
import asyncio
asyncio.get_event_loop().run_forever()
虽然这似乎有效,但它也会阻塞笔记本电脑,并且似乎与笔记本电脑不兼容。
我的理解是Jupyter在幕后使用Tornado,因此我尝试按照Tornado文档中建议的方式安装Tornado事件循环:
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()
然而,这会导致以下错误:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-1-1139449343fc> in <module>()
1 from tornado.platform.asyncio import AsyncIOMainLoop
----> 2 AsyncIOMainLoop().install()
~\AppData\Local\Continuum\Anaconda3\envs\numismatic\lib\site- packages\tornado\ioloop.py in install(self)
179 `IOLoop` (e.g., :class:`tornado.httpclient.AsyncHTTPClient`).
180 """
--> 181 assert not IOLoop.initialized()
182 IOLoop._instance = self
183
AssertionError:
最后我找到了以下页面:http://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Asynchronous.html
因此,我添加了一个单元格,其中包含以下代码:
import asyncio
from ipykernel.eventloops import register_integration
@register_integration('asyncio')
def loop_asyncio(kernel):
'''Start a kernel with asyncio event loop support.'''
loop = asyncio.get_event_loop()
def kernel_handler():
loop.call_soon(kernel.do_one_iteration)
loop.call_later(kernel._poll_interval, kernel_handler)
loop.call_soon(kernel_handler)
try:
if not loop.is_running():
loop.run_forever()
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
接下来的单元格中,我运行了:
%gui asyncio
那样做虽然有效,但我并不真正理解为什么以及它是如何起作用的。有人可以请解释一下吗?