Jupyter笔记本运行await函数

4

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

运行以下代码

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

enter image description here

然而,在Ipython上它能正常工作

enter image description here

1个回答

8

在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'

简述: 在notebook中运行asyncio与后台Tornado 5.0运行的事件循环冲突。第二个选项是将notebook降级到依赖于旧版本Tornado的版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接