将任务添加到 运行ning 循环和 运行 直到完成

add task to running loop and run until complete

我有一个从没有 awaitasync 函数调用的函数,我的函数需要调用 async 函数。我可以用 asyncio.get_running_loop().create_task(sleep()) 来做到这一点,但是顶层的 run_until_complete 在新任务完成之前不会 运行。

如何让事件循环进入 运行 直到新任务完成?

我无法创建我的函数 async 因为它不是用 await.

调用的

我无法更改 futuresleep。我只能控制 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())

nest_asyncio 包似乎可以帮到您。我还在示例中包含了获取任务的 return 值。

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())

结果:

In control
0
1
2
3
4
5
6
7
8
9
Sleep finished
Sleep return
Out of control
[Finished in 10.2s]