Asyncio,等待和无限循环

use*_*289 5 infinite-loop python-3.x python-asyncio discord.py

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

我有一个discord bot,每2秒运行一次任务.我尝试使用无限循环,但是脚本崩溃了,Task was destroyed but it is still pending!我已经阅读了有关asyncio的协同程序的内容,但是我发现await它们都没有使用.await例如,通过运行协同程序可以避免此错误吗?

Mik*_*mov 6

Task was destroyed but it is still pending!当您在脚本中的loop.close()某些任务未完成时调用时收到警告。通常你应该避免这种情况,因为未完成的任务可能不会释放一些资源。您需要在事件循环关闭之前等待任务完成或取消它。

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

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

另请参阅此答案以获取有关任务的更多信息。