0

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

2 Answers 2

1

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!")
Sign up to request clarification or add additional context in comments.

1 Comment

I think this misses the syntax error as line 6, await print_async("This is a top-level async print") which is incorrect since it isn't within a co-routine defn. Remove it and I believe the concurrent programming logic would be valid.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.