Getting values from functions that run as asyncio tasks

前端 未结 3 1734
-上瘾入骨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:01

    The coroutines work as is. Just use the returned value from loop.run_until_complete() and call asyncio.gather() to collect multiple results:

    #!/usr/bin/env python3
    import asyncio
    
    @asyncio.coroutine
    def func_normal():
        print('A')
        yield from asyncio.sleep(5)
        print('B')
        return 'saad'
    
    @asyncio.coroutine
    def func_infinite():
        for i in range(10):
            print("--%d" % i)
        return 'saad2'
    
    loop = asyncio.get_event_loop()
    tasks = func_normal(), func_infinite()
    a, b = loop.run_until_complete(asyncio.gather(*tasks))
    print("func_normal()={a}, func_infinite()={b}".format(**vars()))
    loop.close()
    

    Output

    --0
    --1
    --2
    --3
    --4
    --5
    --6
    --7
    --8
    --9
    A
    B
    func_normal()=saad, func_infinite()=saad2
    

提交回复
热议问题