首页 > 解决方案 > Jupyter notebook 运行等待功能

问题描述

在 Jupyter notebook 上学习协程和任务后,

运行以下代码

import asyncio
async def main():
    print('learn')
    await asyncio.sleep(1)
    print('Jupyter')

在此处输入图像描述

但是,它在 Ipython 上可以正常工作

在此处输入图像描述

标签: python

解决方案


这是更高版本的 Jupyter的一个已知问题。安装nest_asyncio作为解决方法

> pip install nest_asyncio

代码

import asyncio

import nest_asyncio


nest_asyncio.apply()


async def main():
    print("Learn")
    await asyncio.sleep(1)
    print("Jupyter")


asyncio.run(main())
# 'Learn'
# 'Jupyter'

TLDR ; 在笔记本中运行 asyncio 与 Tornado 5.0 在后台运行的现有事件循环冲突。第二种选择是降级notebook到依赖于旧版本 Tornado 的版本。


推荐阅读