我有一些异步代码,它们在Python解释器(CPython 3.6.2)中运行良好。现在,我想在一个带有IPython内核的Jupyter笔记本中运行它。
我可以用以下命令运行它
import asyncio
asyncio.get_event_loop().run_forever()
虽然这似乎有效,但它似乎也阻碍了笔记本电脑,似乎与笔记本电脑玩得不好。
我的理解是Jupyter在引擎盖下使用了龙卷风,所以我尝试了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
这行得通,但我真的不明白为什么和如何行得通。有人能给我解释一下吗?
https://stackoverflow.com/questions/47518874
复制相似问题