Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async function in Python not working as expected

I have the following code snippet:

import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

BEFORE
AFTER

Right now it's

AFTER
BEFORE
like image 972
flowermia Avatar asked Oct 25 '25 15:10

flowermia


1 Answers

run seems to be blocking, so you might want to just use gather here:

import asyncio

async def main():
    await asyncio.gather(work(), setup())
    print('After gather')

async def work():
    await asyncio.sleep(2)
    print("AFTER")

async def setup():
    print("BEFORE")

asyncio.run(main())

This correctly prints

BEFORE
AFTER
After gather

The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.

like image 71
Kraigolas Avatar answered Oct 28 '25 04:10

Kraigolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!