简体   繁体   中英

Python: How to obtain return value from only one function (out of several executed with asyncio.gather)

What is a good way to run functions with asyncio.gather and get the return value from only one of the executed functions? This might be more of a novice Python syntax question than it has to do with asyncio per se but my example script below uses it.

async def interval():
    await asyncio.sleep(10)

async def check_messages():
    received_messages = await check_for_new_messages()
    return received_messages

asyncio def main():
    _interval, received_messages = await asyncio.gather(interval(), check_messages())
    if received_messages:
        # process them

I basically want received_messages back from check_messages() , but interval() doesn't even return a value so it is unneeded. Is there a nicer way of doing this than having to create _interval ?

You are doing it right, you don't need to change anything. You can shorten _interval to _ if it's too long as it is. You can avoid the other variable completely with received_messages = (await asyncio.gather(interval(), check_messages()))[1] , but that's just less readable.

Another option is not to use gather at all, but spawn two tasks and await them. It doesn't lead to less code, but here it is for completeness:

asyncio def main():
    t1 = asyncio.create_task(interval())
    t2 = asyncio.create_task(messaages())
    await t1
    received_messages = await t2
    if received_messages:
        # process them

Note that the above code will run interval() and messages() in parallel, despite the use of await , because both are spawned as tasks prior to the first await - see this answer for a more detailed explanation.

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