Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async/await in python 3.5+

I was trying to explain an example of async programming in python but I failed. Here is my code.

import asyncio
import time

async def asyncfoo(t):
    time.sleep(t)
    print("asyncFoo")


loop = asyncio.get_event_loop()
loop.run_until_complete(asyncfoo(10)) # I think Here is the problem
print("Foo")
loop.close()

My expectation is that I would see:

Foo
asyncFoo

With a wait of 10s before asyncFoo was displayed.

But instead I got nothing for 10s, and then they both displayed.

What am I doing wrong, and how can I explain it?

like image 300
Rahul Avatar asked Dec 22 '16 12:12

Rahul


People also ask

How do I use async await in Python?

An async function uses the await keyword to denote a coroutine. When using the await keyword, coroutines release the flow of control back to the event loop. To run a coroutine, we need to schedule it on the event loop. After scheduling, coroutines are wrapped in Tasks as a Future object.

Is there async await in Python?

Python's asyncio package (introduced in Python 3.4) and its two keywords, async and await , serve different purposes but come together to help you declare, build, execute, and manage asynchronous code.

When did Python add async await?

Python added support for async/await with version 3.5 in 2015 adding 2 new keywords, async and await . TypeScript added support for async/await with version 1.7 in 2015. Javascript added support for async/await in 2017 as part of ECMAScript 2017 JavaScript edition.

Can I use await async?

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError .


1 Answers

run_until_complete will block until asyncfoo is done. Instead, you would need two coroutines executed in the loop. Use asyncio.gather to easily start more than one coroutine with run_until_complete.

Here is a an example:

import asyncio


async def async_foo():
    print("asyncFoo1")
    await asyncio.sleep(3)
    print("asyncFoo2")


async def async_bar():
    print("asyncBar1")
    await asyncio.sleep(1)
    print("asyncBar2")


loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(async_foo(), async_bar()))
loop.close()
like image 50
Udi Avatar answered Oct 19 '22 23:10

Udi