异步、等待和无限循环

Asyncio, await and infinite loops

async def start(channel):
    while True:
        m = await client.send_message(channel, "Generating... ")
        generator.makeFile()
        with open('tmp.png', 'rb') as f:
            await client.send_file(channel, f) 
        await client.delete_message(m)
        await asyncio.sleep(2)

我有一个每 2 秒运行一次任务的 discord 机器人。我尝试为此使用无限循环,但脚本因 Task was destroyed but it is still pending! 而崩溃 我已阅读有关 asyncio 协程的信息,但我发现的示例中有 none 在其中使用了 await。例如,是否可以通过 运行 与 await 的协程来避免此错误?

Task was destroyed but it is still pending! 警告您在调用 loop.close() 时收到警告,其中一些 tasks in your script aren't finished. Usually you should avoid this situation because unfinished task may not release some resources. You need either to await task done or cancel 在事件循环关闭之前收到。

由于您有无限循环,您可能需要取消任务,例如:

import asyncio
from contextlib import suppress


async def start():
    # your infinite loop here, for example:
    while True:
        print('echo')
        await asyncio.sleep(1)


async def main():
    task = asyncio.Task(start())

    # let script some thime to work:
    await asyncio.sleep(3)

    # cancel task to avoid warning:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task  # await for task cancellation


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

有关任务的更多信息,另请参阅