2017-07-08 71 views
3
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秒运行一次任务。我试着用一个无限循环来做这个,但脚本崩溃了Task was destroyed but it is still pending!我已经阅读了关于asyncio的协同程序,但是我发现没有一个例子使用await。例如,运行一个协程为await可以避免这个错误吗?Asyncio,等待和无限循环

+0

'await'在这里不是问题。更多'while True'也是定期调用的常用方式(https://stackoverflow.com/questions/37512182/how-can-i-periodically-execute-a-function-with-asyncio)。显示如何执行该功能,你是否试图停止代码中的任务? – kwarunek

回答

2

Task was destroyed but it is still pending!当您的脚本中的某些tasks未完成时,您会收到当您拨打loop.close()时收到的警告。通常你应该避免这种情况,因为未完成的任务可能不会释放一些资源。您需要等待已完成的任务,或者在事件循环关闭之前执行任务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() 

this answer请参阅有关任务的详细信息。

+0

[该答案](https://stackoverflow.com/a/37345564/1113207)完美解决它,谢谢。 这个例子运行良好,但似乎要求无限循环会停止在某个点或另一个点。 – user8245289