Python asyncio: stop the loop when one coroutine is done
<p>I'm quite new in this python asyncio topic. I have a simple question:
I have a task containing two coroutines to be run concurrently. First coroutine(my_coroutine) would just print something continuously until second_to_sleep is reached. The second coroutine(seq_coroutine) would call 4 other coroutines sequentially one after the other. My goal is to stop the loop at the end of seq_coroutine whenever it is completely finished. To be exact, I want my_coroutine be alive until seq_coroutine is finished. Can someone help me with that?</p>

<p>My code is like this:</p>

<pre><code>import asyncio

async def my_coroutine(task,  seconds_to_sleep = 3):
    print("{task_name} started\n".format(task_name=task))
    for i in range(1, seconds_to_sleep):
        await asyncio.sleep(1)
        print("\n{task_name}: second {seconds}\n".format(task_name=task, seconds=i))

async def coroutine1():
    print("coroutine 1 started")
    await asyncio.sleep(1)
    print("coroutine 1 finished\n")


async def coroutine2():
    print("coroutine 2 started")
    await asyncio.sleep(1)
    print("coroutine 2 finished\n")


async def coroutine3():
    print("coroutine 3 started")
    await asyncio.sleep(1)
    print("coroutine 3 finished\n")


async def coroutine4():
    print("coroutine 4 started")
    await asyncio.sleep(1)
    print("coroutine 4 finished\n")


async def seq_coroutine():
    await coroutine1()
    await coroutine2()
    await coroutine3()
    await coroutine4()

def main():
    main_loop = asyncio.get_event_loop()
    task = [asyncio.ensure_future(my_coroutine("task1", 11)),
            asyncio.ensure_future(seq_coroutine())]
    try:
        print('loop is started\n')
        main_loop.run_until_complete(asyncio.gather(*task))
    finally:
        print('loop is closed')
        main_loop.close()


if __name__ == "__main__":
    main()
</code></pre>

<p>This is the output of this program:</p>

<pre><code>loop is started

task1 started

coroutine 1 started

task1: second 1

coroutine 1 finished
coroutine 2 started

task1: second 2

coroutine 2 finished
coroutine 3 started

task1: second 3

coroutine 3 finished
coroutine 4 started

task1: second 4

coroutine 4 finished

task1: second 5
task1: second 6
task1: second 7
task1: second 8
task1: second 9
task1: second 10

loop is closed
</code></pre>

<p>I only want to have something like this:</p>

<pre><code>loop is started

task1 started

coroutine 1 started

task1: second 1

coroutine 1 finished
coroutine 2 started

task1: second 2

coroutine 2 finished
coroutine 3 started

task1: second 3

coroutine 3 finished
coroutine 4 started

task1: second 4

coroutine 4 finished

loop is closed
</code></pre>

<p>I just found a suitable solution for my problem.
I won't remove my post and I'll post my solution so that it may help others who face the same question.
I used <code>asyncio.wait(task, return_when=asyncio.FIRST_COMPLETED)</code> and it will return the result whenever the first task is finished.
This is the solution:</p>

<pre><code>import asyncio
from asyncio.tasks import FIRST_COMPLETED
from concurrent.futures import CancelledError

async def my_coroutine(task,  seconds_to_sleep = 3):
    print("{task_name} started\n".format(task_name=task))
    for i in range(1, seconds_to_sleep):
        await asyncio.sleep(1)
        print("\n{task_name}: second {seconds}\n".format(task_name=task, seconds=i))

async def coroutine1():
    print("coroutine 1 started")
    await asyncio.sleep(1)
    print("coroutine 1 finished\n")


async def coroutine2():
    print("coroutine 2 started")
    await asyncio.sleep(1)
    print("coroutine 2 finished\n")


async def coroutine3():
    print("coroutine 3 started")
    await asyncio.sleep(1)
    print("coroutine 3 finished\n")


async def coroutine4():
    print("coroutine 4 started")
    await asyncio.sleep(1)
    print("coroutine 4 finished\n")


async def seq_coroutine(loop):
    await coroutine1()
    await coroutine2()
    await coroutine3()
    await coroutine4()

def main():
    main_loop = asyncio.get_event_loop()
    task = [asyncio.ensure_future(my_coroutine("task1", 11)),
            asyncio.ensure_future(seq_coroutine(main_loop))]
    try:
        print('loop is started\n')
        done, pending = main_loop.run_until_complete(asyncio.wait(task, return_when=asyncio.FIRST_COMPLETED))
        print("Completed tasks: {completed}\nPending tasks: {pending}".format(completed = done, pending = pending))

        #canceling the tasks
        for task in pending:
            print("Cancelling {task}: {task_cancel}".format(task=task, task_cancel=task.cancel()))

    except CancelledError as e:
        print("Error happened while canceling the task: {e}".format(e=e))
    finally:
        print('loop is closed')


if __name__ == "__main__":
    main()
</code></pre>

python coroutine python-asyncio