删除/销毁完成期货asyncio Python

问题描述:

我有一个Python脚本,它使用asyncio来创建超过一百万个请求。我首先遇到了内存问题,然后发现了信号量,之后我成功实现了一个信号量来同时限制并发任务的数量以及队列中的任务。删除/销毁完成期货asyncio Python

我的程序加载这样的请求的列表:

 with open(wordlist) as words: 
      w = words.read().splitlines() 

然后该列表被传递到下面的函数进行处理,实际完成工作。

async def _process_dns_wordlist(self, wordlist, domain): 
    """Takes a list of words and adds them to the task list as space is available""" 
    for word in wordlist: 
     # Wait on the semaphore before adding more tasks 
     await self.sem.acquire() 
     host = '{}.{}'.format(word, domain) 
     task = asyncio.ensure_future(self._dns_lookup(host)) 
     task.add_done_callback(functools.partial(self._dns_result_callback, host)) 
     self.tasks.append(task) 
    await asyncio.gather(*self.tasks, return_exceptions=True) 

之前,我实现了信号的程序只会崩溃,跑出来的时候,我排队的所有任务的内存,现在它运行一段时间,然后崩溃,因为它运行的内存大约1/2的方式通过请求。

我认为这是因为在未来由我的回调处理之后,它在内存中浪费空间。我的问题是,我无法弄清楚在完成处理后的未来时如何使用它来删除处理的未来。我读过asyncio文档,但没有看到销毁/删除方法。我错过了真正明显的东西吗?

感谢您的帮助!

事实证明,答案很简单,但我不确定这是否是正确的方法。

在我的回调,我做处理结果,我这样做后:

self.tasks.remove(future) 

这成功地解决了我的记忆问题。如果你有更好的方法来处理这个问题,请让我知道!