Amir Afghani
Amir Afghani

Reputation: 38541

Jupyter Notebook Async functions

In the code below, I'd like the following behavior:

When the user clicks the button I've defined in App Mode, I want the print_async routine inside of it to be invoked, which waits for 2 seconds and then prints ""this is async print from buttonCLicked", then I want the print after which is "button clicked!" to appear. Instead what I get is an interpreter error:

Any help appreciated.

File "cell_name", line 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

Upvotes: 0

Views: 2414

Answers (2)

saravana_kumaran
saravana_kumaran

Reputation: 1

First of all, You cannot use await keyword outside async function. If that is the entry point to your asynchronous program, use asyncio.run() function with function call as a parameter to run() method to call that co-routine.

Upvotes: 0

jakevdp
jakevdp

Reputation: 86433

You can do this with the asyncio.run function (Requires Python 3.7 or newer):

In your code it would look like this:

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

Upvotes: 1

Related Questions