Asyncio in Python: simplest example

This is a script to try to understand how asyncio works:

import asyncio


counter = 0


async def talk(name, script):

    print(f"Enters", end = " ")
    for act in script:
        print(f"{name}: {act}")
        await asyncio.sleep(5)
    print(f"{name} exit...\n")


def startloop():
    loop = asyncio.get_event_loop()
    tasks = [
        loop.create_task(talk("Ross", [
            "I am good",
            "I am better than you",
            "absolutely"])),
        loop.create_task(talk("Mark", [
            "Me too!\n",
            "Really?\n",
            "What a stupid guy!\n",
            "I am done\n",
            ])),
    ]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    print("\nThe End")

startloop()

This is the output, but watch the video to understand what it really does

Enters Ross: I am good
Enters Mark: Me too!

Ross: I am better than you
Mark: Really?

Ross: absolutely
Mark: What a stupid guy!

Ross exit...

Mark: I am done

Mark exit...


The End

Video explanation


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts