Skip to content
Advertisement

add task to running loop and run until complete

I have a function called from an async function without await, and my function needs to call async functions. I can do this with asyncio.get_running_loop().create_task(sleep()) but the run_until_complete at the top level doesn’t run until the new task is complete.

How do I get the event loop to run until the new task is complete?

I can’t make my function async because it’s not called with await.

I can’t change future or sleep. I’m only in control of in_control.

import asyncio


def in_control(sleep):
    """
    How do I get this to run until complete?
    """
    return asyncio.get_running_loop().create_task(sleep())


async def future():
    async def sleep():
        await asyncio.sleep(10)
        print('ok')

    in_control(sleep)


asyncio.get_event_loop().run_until_complete(future())

Advertisement

Answer

It appears that the package nest_asyncio will help you out here. I’ve also included in the example fetching the return value of the task.

import asyncio
import nest_asyncio


def in_control(sleep):
    print("In control")
    nest_asyncio.apply()
    loop = asyncio.get_running_loop()
    task = loop.create_task(sleep())
    loop.run_until_complete(task)
    print(task.result())
    return


async def future():
    async def sleep():
        for timer in range(10):
            print(timer)
            await asyncio.sleep(1)
        print("Sleep finished")
        return "Sleep return"

    in_control(sleep)
    print("Out of control")


asyncio.get_event_loop().run_until_complete(future())

Result:

In control
0
1
2
3
4
5
6
7
8
9
Sleep finished
Sleep return
Out of control
[Finished in 10.2s]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement