首页 > 解决方案 > 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

标签: jupyter-notebookpython-asyncio

解决方案


您可以使用该asyncio.run函数执行此操作(需要 Python 3.7 或更高版本):

在您的代码中,它看起来像这样:

def onButtonClicked(_):
    asyncio.run(print_async("this is async print from buttonCLicked"))
    print("button clicked!")

推荐阅读