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

Jay*_*yen 5 python python-asyncio

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

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

我无法执行我的函数,async因为它不是用 调用的await

我无法改变future或者sleep。我只能控制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())
Run Code Online (Sandbox Code Playgroud)

Da *_*cky 3

看起来这个包nest_asyncio可以帮助你。我还在示例中包含了获取任务返回值的内容。

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())
Run Code Online (Sandbox Code Playgroud)

结果:

In control
0
1
2
3
4
5
6
7
8
9
Sleep finished
Sleep return
Out of control
[Finished in 10.2s]
Run Code Online (Sandbox Code Playgroud)