【发布时间】:2017-11-27 19:58:57
【问题描述】:
我有一些在 Python 解释器 (CPython 3.6.2) 中运行良好的异步代码。我现在想在带有 IPython 内核的 Jupyter notebook 中运行它。
我可以运行它
import asyncio
asyncio.get_event_loop().run_forever()
虽然这似乎可行,但它似乎也阻止了笔记本,并且似乎与笔记本不兼容。
我的理解是 Jupyter 在后台使用 Tornado,所以我尝试install a Tornado event loop as recommended in the Tornado docs:
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
这行得通,但我真的不明白它为什么以及如何工作。有人可以向我解释一下吗?
【问题讨论】:
标签: python ipython-notebook jupyter python-asyncio