简体   繁体   中英

return a value from while loop when using asyncio function

I am trying to connect and recieve messages from multiple websockets concurrently. For this purpose I made it with asyncio, and it prints messages correctly. But the problem is that I just can print it, not return it.

The simplified example of pseudo code which I am struggle with is as below:

import websockets
import json

symbols_id = [1,2]

## LOOP RUNNING EXAMPLE OF ASYNCIO
async def get_connect(symbols_id):
    tasks = []
    for _id in symbols_id:
        print('conncetion to', _id)
        if _id == 1:
            a = 0
        elif _id == 2:
            a = 200
        tasks.append(asyncio.create_task(_loop(a)))

    return tasks

async def _loop(a):
    while True:
        print(a)
        a+=1
        await asyncio.sleep(2.5)

async def ping_func():
    while True:
        print('------ ping')
        await asyncio.sleep(5)


async def main():
    tasks = await get_connect(symbols_id)
    asyncio.create_task(ping_func())
    await asyncio.gather(*tasks)

asyncio.run(main())

As you can see from the code above I used print(a) to print a in each loop. I test return a instead of print(a) but it was not helpful.

thanks

yield a ? return a will exit the function and the loop, yield is usually what you want in asyncio for looped tasks

Finally I found the way of using yield and async for to read data in each loop. It will work correctly, by changing the code to the following one.

import websockets
import json

symbols_id = [1,2]

global a
a=0

## LOOP RUNNING EXAMPLE OF ASYNCIO
async def get_connect(symbols_id):
    tasks = []
    for _id in symbols_id:
        print('conncetion to', _id)
        if _id == 1:
            a = 0
        elif _id == 2:
            a = 200
        tasks.append(asyncio.create_task(_loop(a)))

    return tasks

async def _loop(param):
    global a
    a = param
    while True:
        print(a)
        a+=1
        await asyncio.sleep(2.5)

async def ping_func():
    while True:
        print('------ ping')
        await asyncio.sleep(5)

async def get_result():
    global a
    while True:
        yield a
        await asyncio.sleep(1)

async def main():
    tasks = await get_connect(symbols_id)
    asyncio.create_task(ping_func())
    async for x in get_result():
        print(x)
    await asyncio.gather(*tasks)

asyncio.run(main())

I was confused with how to use generated data from this code snippet inside the other code snippet. what I found is:

1- Generated data can be accessible with global variables.

2- By defining a class and a property, it can be accessible from every part of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM