Developer Snippet Diary

Async (asyncio) await in Python

asyncio lets your program do multiple tasks at the same time without waiting.

import asyncio
async def hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")
asyncio.run(hello())

Multiple tasks:

gather accept multiple functions-> run all at same time, -> wait for finish all ->return results if any
ie Order 2 dishes and wait at table ???????

import asyncio

async def task1():
    await asyncio.sleep(2)
    print("Task 1 done")

async def task2():
    await asyncio.sleep(1)
    print("Task 2 done")

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

output:

Task 2 done
Task 1 done

Creating Tasks: runs in background
Starts task in background immediately
ie Order food, then go do shopping ????, come back later

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

async def main():
    task = asyncio.create_task(work())
    print("Doing other things...")
    await task

asyncio.run(main())

 

code:

import asyncio

async def work(i):
    print(f"Start {i}")
    await asyncio.sleep(2)
    print(f"End {i}")

async def main():
    await asyncio.gather(*(work(i) for i in range(5)))

asyncio.run(main())

output:

Start 0
Start 1
Start 2
Start 3
Start 4
End 0
End 1
End 2
End 3
End 4

Fetch multiple urls:

import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    urls = [
        "https://example.com",
        "https://google.com"
    ]
    
    tasks = [fetch(url) for url in urls]
    results = await asyncio.gather(*tasks)

    print("Fetched", len(results), "pages")

asyncio.run(main())

 

Semaphore: ???? Only N tasks run at once

sem = asyncio.Semaphore(2)

async def work(i):
    async with sem:
        print(f"Task {i} running")
        await asyncio.sleep(2)

async def main():
    await asyncio.gather(*(work(i) for i in range(5)))

asyncio.run(main())

Queue:

import asyncio

queue = asyncio.Queue()

async def producer():
    for i in range(5):
        await queue.put(i)
        print("Produced", i)

async def consumer():
    while True:
        item = await queue.get()
        print("Consumed", item)
        queue.task_done()

async def main():
    asyncio.create_task(consumer())
    await producer()
    await queue.join()

asyncio.run(main())
Posted by: R GONDAL
Email: rizikmw@gmail.com