Snippets Python / Asyncio Examples

Asyncio Examples

By Marcelo Fernandes Sep 16, 2017

Examples

Just a few examples that might be useful.

Example 1: Running with async def


import asyncio


async def foo():
    print('Running in foo')
    # Using await we declare that the coroutine
    # may give the control back to the event loop.
    await asyncio.sleep(0)
    print('Explicit context switch to foo again')


async def bar():
    print('Explicit context to bar')
    await asyncio.sleep(0)
    print('Implicit context switch back to bar')


loop = asyncio.get_event_loop()

# Coroutines can only be called from other coroutines, or be
# wrapped in a task and then scheduled, we use create_task for that.
tasks = [loop.create_task(foo()), loop.create_task(bar())]

# Wait for the Futures and Coroutines objects given
# by the first argument (tasks), to complete.
# This variable is gonna be a Generator object waiting to be run.
# Here, we basically say: Create a new task, that waits
# for the other two tasks to complete using wait.
wait_tasks = asyncio.wait(tasks)

# Blocking call that waits for all tasks to succeed
loop.run_until_complete(wait_tasks)
loop.close()



Example 2: Playing with multiple tasks


import time
import asyncio

start = time.time()


def tic():
    return 'at %1.1f seconds' % (time.time() - start)


async def gr1():
    # Busy waits for a second, but we don't want to stick around...
    print('gr1 started work: {}'.format(tic()))
    await asyncio.sleep(2)
    print('gr1 ended work: {}'.format(tic()))


async def gr2():
    # Busy waits for a second, but we don't want to stick around...
    print('gr2 started work: {}'.format(tic()))
    await asyncio.sleep(2)
    print('gr2 Ended work: {}'.format(tic()))


async def gr3():
    print("Let's do some stuff while the coroutines are blocked, {}".format(tic()))
    await asyncio.sleep(1)
    print("Done!")


loop = asyncio.get_event_loop()

tasks = [
    loop.create_task(gr1()),
    loop.create_task(gr2()),
    loop.create_task(gr3())
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()




Example 3: Synchronous and Asynchronous


import random
from time import sleep
import asyncio


def task(pid):
    """Synchronous non-deterministic task.
    """
    sleep(random.randint(0, 2) * 0.001)
    print('Task %s done' % pid)


async def task_coro(pid):
    """Coroutine non-deterministic task
    """
    await asyncio.sleep(random.randint(0, 2) * 0.001)
    print('Task %s done' % pid)


def synchronous():
    for i in range(1, 10):
        task(i)


async def asynchronous():
    # ensure_future schedules the execution of a coroutine object: Wrap it
    # in a future. And return a task object. If the argument is a Future,
    # it is returned directly. We just want to make sure that those tasks
    # are futures.
    tasks = [asyncio.ensure_future(task_coro(i)) for i in range(1, 10)]
    await asyncio.wait(tasks)


print('Synchronous:')
synchronous()

ioloop = asyncio.get_event_loop()
print('Asynchronous:')
ioloop.run_until_complete(asynchronous())
ioloop.close()



Example 4: Starting with @asyncio.coroutine


import asyncio


@asyncio.coroutine
def create():
    print("Started - Creating a file")
    yield from asyncio.sleep(3.0)
    print("(1) create file")


@asyncio.coroutine
def write():
    print("Started - Writing a file")
    yield from asyncio.sleep(1.0)
    print("(2) write into file")


@asyncio.coroutine
def close():
    print("Started - Closing a file")
    print("(3) close file")


@asyncio.coroutine
def test():
    yield from create()
    yield from write()
    yield from close()
    yield from asyncio.sleep(2.0)
    loop.stop()

loop = asyncio.get_event_loop()
asyncio.ensure_future(test())
loop.run_forever()
print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
loop.close()



Example 5: Using callbacks


import asyncio


@asyncio.coroutine
def my_coroutine(future, task_name, seconds_to_sleep=3):
    print('{0} sleeping for: {1} seconds'.format(task_name, seconds_to_sleep))
    yield from asyncio.sleep(seconds_to_sleep)
    future.set_result('{0} is finished'.format(task_name))


def got_result(future):
    print(future.result())


loop = asyncio.get_event_loop()
future1 = asyncio.Future()
future2 = asyncio.Future()

tasks = [
    my_coroutine(future1, 'task1', 3),
    my_coroutine(future2, 'task2', 1)]

future1.add_done_callback(got_result)
future2.add_done_callback(got_result)

loop.run_until_complete(asyncio.wait(tasks))
loop.close()



Notes


References:


link 1