jupyter-notebook - Jupyter Notebook 异步函数
问题描述
在下面的代码中,我想要以下行为:
当用户单击我在应用程序模式中定义的按钮时,我希望调用其中的 print_async 例程,该例程等待 2 秒,然后打印“这是来自 buttonCLicked 的异步打印”,然后我想要打印之后这是“单击按钮!”出现。相反,我得到的是解释器错误:
任何帮助表示赞赏。
文件“cell_name”,第 6 行 SyntaxError: 'await' outside async function
from IPython.display import display
from ipywidgets import widgets
import asyncio
#DO NOT CHANGE THIS CELL
#Define an async function
async def print_async(message):
await asyncio.sleep(2)
print(message)
# Show that we can print from the top-level jupyter terminal
await print_async("This is a top-level async print")
#Define a callback function for the button
def onButtonClicked(_):
await print_async("this is async print from buttonCLicked")
print("button clicked!")
button = widgets.Button(
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon=''
)
button.on_click(onButtonClicked)
display(button)
button = widgets.Button(
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon=''
)
button.on_click(onButtonClicked)
display(button)
Goal: Get the button click to call the print_async method
解决方案
您可以使用该asyncio.run
函数执行此操作(需要 Python 3.7 或更高版本):
在您的代码中,它看起来像这样:
def onButtonClicked(_):
asyncio.run(print_async("this is async print from buttonCLicked"))
print("button clicked!")
推荐阅读
- flutter - Flutter 优化 TextField 自动完成实现中的 API 调用次数
- self-signed-certificate - 使用 ProtonBridge 和 mbsync 获取自签名证书错误
- azure - 使用新的 Azure 开发人员门户,如何在索引上添加一个以用户登录为条件的按钮?
- sql - 更新数据以将其集成到我的数据仓库中
- reactjs - 如何结合自定义钩子来获取数据和上下文?
- android - 使用 RecyclerView 和数据库进行双重数据维护
- java - 如何使用 DeltaSpike 和 Weld 设置 SparkJava CDI
- laravel - Laravel,多个模型之间的多对多关系
- laravel - Laravel:反向 WHERE NOT IN - 排除任何具有 id=XXX 子级的父表
- sharepoint - 如何防止 Sharepoint 添加新列表项限制超过 5 个,而不是查看项目