如何永远 运行 异步函数 (Python)

How to run async function forever (Python)

如何永远使用 asyncio 和 运行 函数。我知道有 run_until_complete(function_name) 但我如何使用 run_forever 如何调用异步函数?

async def someFunction():
    async with something as some_variable:
        # do something

我不知道如何启动该功能。

我不确定你说的到底是什么意思我不确定如何启动该功能。如果您按字面意思问问题:

loop = asyncio.get_event_loop()
loop.run_forever()

如果您希望在初始化循环之前将函数添加到循环中,那么 loop.run_forever() 之前的以下行就足够了:

asyncio.async(function())

要将函数添加到已经 运行 的循环中,您需要 ensure_future:

asyncio.ensure_future(function(), loop=loop)

在这两种情况下,您打算调用的函数必须以某种方式指定为异步函数,即使用 async 函数前缀或 @asyncio.coroutine 装饰器。

run_forever 并不意味着异步函数会神奇地 运行 永远,它意味着 loop 将永远 运行,或者至少直到有人打电话给 loop.stop()。要从字面上 运行 永远使用异步函数,您需要创建一个异步函数来执行此操作。例如:

async def some_function():
    async with something as some_variable:
        # do something

async def forever():
    while True:
        await some_function()

loop = asyncio.get_event_loop()
loop.run_until_complete(forever())

这就是为什么 run_forever() 不接受参数,它不关心任何特定的协程。典型的模式是使用 loop.create_task or equivalent before invoking run_forever(). But even an event loop that runs no tasks whatsoever and sits idly can be useful since another thread can call asyncio.run_coroutine_threadsafe 添加一些协同程序并使其工作。