【问题标题】:Jupyter Notebook Async functionsJupyter Notebook 异步函数
【发布时间】:2020-01-08 00:45:16
【问题描述】:

在下面的代码中,我想要以下行为:

当用户单击我在应用程序模式中定义的按钮时,我希望调用其中的 print_async 例程,该例程等待 2 秒,然后打印“”这是来自 buttonCLicked 的异步打印“,然后我想要之后的打印是“按钮单击!”出现。相反,我得到的是解释器错误:

任何帮助表示赞赏。

文件“cell_name”,第 6 行 SyntaxError: 'await' 在异步函数之外

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-notebook python-asyncio


    【解决方案1】:

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

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

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

    【讨论】:

    • 我认为这遗漏了第 6 行 await print_async("This is a top-level async print") 的语法错误,这是不正确的,因为它不在协程定义中。删除它,我相信并发编程逻辑是有效的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2018-11-07
    • 1970-01-01
    • 2019-11-24
    • 2017-05-09
    • 2018-07-17
    相关资源
    最近更新 更多