Home > Software engineering >  How do I terminate an asyncio loop in these conditions?
How do I terminate an asyncio loop in these conditions?

Time:10-18

I am creating a python code that does the following:

1 - creates an asynchronous function called "nums" than prints random numbers from 0 to 10 every 2 seconds. 2 - execute a function that prints "hello world" every 5 seconds. 3 - if the function "nums" prints 1 or 3, break the loop and end the program.

The thing is, it's not breaking out of the loop. What I am supposed to do? Thank you.

import asyncio
import random

async def nums():
    while True:
        x = print(random.randint(0, 10))
        await asyncio.sleep(2)
        if x == 1 or x == 3:
            break

async def world():
    while True:
        print("hello world")
        await asyncio.sleep(5)

async def main():
    while True:
        await asyncio.wait([nums(), world()])

if __name__ == '__main__':
    asyncio.run(main())

CodePudding user response:

You can use return_when=asyncio.FIRST_COMPLETED parameter in asyncio.wait:

import asyncio
import random


async def nums():
    while True:
        x = random.randint(0, 10)
        print(x)
        if x in {1, 3}
            break
        await asyncio.sleep(2)


async def world():
    while True:
        print("hello world")
        await asyncio.sleep(5)


async def main():
    task1 = asyncio.create_task(nums())
    task2 = asyncio.create_task(world())
    await asyncio.wait({task1, task2}, return_when=asyncio.FIRST_COMPLETED)


if __name__ == "__main__":
    asyncio.run(main())

Prints (for example):

5
hello world
6
6
hello world
1

<program ends here>
  • Related