Getting values from functions that run as asyncio tasks

前端 未结 3 1731
-上瘾入骨i
-上瘾入骨i 2021-02-06 20:28

I was trying the following code:

import asyncio

@asyncio.coroutine
def func_normal():
        print(\"A\")
        yield from asyncio.sleep(5)
        print(\"B         


        
3条回答
  •  无人共我
    2021-02-06 21:14

    loop.run_until_complete returns the value returned by the function you pass into it. So, it will return the output of asyncio.wait:

    import asyncio
    
    @asyncio.coroutine
    def func_normal():
        print("A")
        yield from asyncio.sleep(5)
        print("B")
        return 'saad'
    
    @asyncio.coroutine
    def func_infinite():
        i = 0
        while i<10:
            print("--"+str(i))
            i = i+1
        return('saad2')
    
    loop = asyncio.get_event_loop()
    
    tasks = [
        asyncio.async(func_normal()),
        asyncio.async(func_infinite())]
    
    done, _ = loop.run_until_complete(asyncio.wait(tasks))
    for fut in done:
        print("return value is {}".format(fut.result()))
    loop.close()
    

    Output:

    A
    --0
    --1
    --2
    --3
    --4
    --5
    --6
    --7
    --8
    --9
    B
    return value is saad2
    return value is saad
    

    You can also access the results directly from the tasks array:

    print(tasks[0].result())
    print(tasks[1].result())
    

提交回复
热议问题