如何在Jupyter笔记本中运行Python的asyncio代码?

2024-05-07 01:13:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些在Python解释器(CPython 3.6.2)中运行良好的异步代码。我现在想在一个带有IPython内核的Jupyter笔记本中运行这个。

我可以用它

import asyncio
asyncio.get_event_loop().run_forever()

虽然这似乎起作用,但似乎也挡住了笔记本,似乎玩笔记本不好。

我的理解是朱庇特在引擎盖下使用龙卷风,所以我试图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

但我真的不明白为什么会这样。有人能给我解释一下吗?


Tags: installruninfromimportloopeventasyncio
3条回答

这不再是最新的jupyter版本中的问题!

https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7

只需编写一个异步函数,然后直接在jupyter单元中等待它。

async def fn():
  print('hello')
  await asyncio.sleep(1)
  print('world')

await fn()

编辑2019年2月21日:问题已解决

This is no longer an issue on the latest version of Jupyter Notebook. Authors of Jupyter Notebook detailed the case here.

下面的答案是op标记正确的原始响应


这是很久以前发布的,但如果其他人正在寻找一个解释和解决的问题运行异步代码在Jupyter笔记本

Jupyter的Tornado 5.0在添加了自己的asyncio事件循环之后更新了砖砌异步功能:

Terminal output of <code>get_event_loop()</code>Jupyter Notebook output of <code>get_event_loop()</code>

因此,对于要在Jupyter笔记本上运行的任何异步功能,您不能调用run_until_complete(),因为您将从asyncio.get_event_loop()接收的循环将处于活动状态。

相反,必须将任务添加到当前循环:

import asyncio
loop = asyncio.get_event_loop()
loop.create_task(some_async_function())

Jupyter笔记本上运行的一个简单示例:

enter image description here

我最近遇到了无法在Jupyter笔记本中运行异步代码的问题。这个问题在这里讨论:https://github.com/jupyter/notebook/issues/3397

我在讨论中尝试了其中一个解决方案,到目前为止解决了这个问题。

pip3 install tornado==4.5.3

这取代了默认安装的tornado 5.x版。

然后,Jupyter笔记本中的异步代码按预期运行。

相关问题 更多 >