Skip to content Skip to sidebar Skip to footer

Asyncio Get Result From Coroutine

I have a task make communication between coroutines with help asyncio and python3. Please tell me how to do it,if one coroutine,in while tru cycle , return value at different inte

Solution 1:

The solution was found with the help of the asyncio.Queue()

import asyncio

@asyncio.coroutine
def get_work(task, work_queue):
    while not work_queue.empty():
        print(task)
        queue_item = yield from work_queue.get()
        print('{0} grabbed item: {1}'.format(task, queue_item))
        yield from asyncio.sleep(0.5)
    asyncio.async(get_work(task, work_queue))

# @asyncio.coroutine

i = 0
async def do_work(task, work_queue):
    global i
    print(task)
    while work_queue.empty():
        work_queue.put_nowait(i)
        i += 1
        await asyncio.sleep(2)
        break
    # asyncio.async(do_work())
    print("Dfgdfg")
    asyncio.ensure_future(do_work(task, work_queue))




if __name__ == "__main__":
    queue_obj = asyncio.Queue()
    loop = asyncio.get_event_loop()

    tasks = [
        asyncio.async(do_work('Run do_work', queue_obj)),
        asyncio.async(get_work('Run get_work', queue_obj))]

    loop.run_until_complete(asyncio.wait(tasks))
    loop.run_forever()

Post a Comment for "Asyncio Get Result From Coroutine"