首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Jupyter笔记本中运行Python异步代码?

如何在Jupyter笔记本中运行Python异步代码?
EN

Stack Overflow用户
提问于 2017-11-28 03:58:58
回答 3查看 30.4K关注 0票数 55

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

我可以用以下命令运行它

代码语言:javascript
复制
import asyncio
asyncio.get_event_loop().run_forever()

虽然这似乎有效,但它似乎也阻碍了笔记本电脑,似乎与笔记本电脑玩得不好。

我的理解是Jupyter在引擎盖下使用了龙卷风,所以我尝试了install a Tornado event loop as recommended in the Tornado docs

代码语言:javascript
复制
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()

但是,这会产生以下错误:

代码语言:javascript
复制
---------------------------------------------------------------------------
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

所以我用下面的代码添加了一个单元格:

代码语言:javascript
复制
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()

在下一个单元格中,我运行:

代码语言:javascript
复制
%gui asyncio

这行得通,但我真的不明白为什么和如何行得通。有人能给我解释一下吗?

EN

回答 3

Stack Overflow用户

发布于 2018-12-02 23:30:56

在最新的jupyter版本中,这不再是一个问题!

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

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

代码语言:javascript
复制
async def fn():
  print('hello')
  await asyncio.sleep(1)
  print('world')

await fn()
票数 43
EN

Stack Overflow用户

发布于 2019-05-21 22:41:17

我和Asyncio在Jupyter中的顿悟时刻是这样的:

代码语言:javascript
复制
import time,asyncio

async def count():
    print("count one")
    await asyncio.sleep(1)
    print("count four")

async def count_further():
    print("count two")
    await asyncio.sleep(1)
    print("count five")

async def count_even_further():
    print("count three")
    await asyncio.sleep(1)
    print("count six")

async def main():
    await asyncio.gather(count(), count_further(), count_even_further())

s = time.perf_counter()
await main()
elapsed = time.perf_counter() - s
print(f"Script executed in {elapsed:0.2f} seconds.")

输出:

代码语言:javascript
复制
count one
count two
count three
count four
count five
count six
Script executed in 1.00 seconds.

最初是从这里开始的,但示例一开始对我来说并不清楚:https://realpython.com/async-io-python/

票数 13
EN

Stack Overflow用户

发布于 2018-07-20 19:03:13

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

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

pip3 install tornado==4.5.3

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47518874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档