当使用多处理和请求组合时,有没有更好的方法来避免内存泄漏?

2024-04-25 14:29:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用请求模块和多处理来处理单个目标。你知道吗

我正在使用池和多处理异步。你知道吗

每个进程发送一系列连续的请求,在每个请求中我随机切换头(用户代理)和代理。你知道吗

过了一段时间,我注意到电脑慢了下来,所有的请求在所有的脚本上都失败了。你知道吗

经过一番挖掘,我意识到问题不在于代理,而在于请求中的内存泄漏。你知道吗

我读过其他关于多处理内存泄漏的文章。你知道吗

我的问题是,有没有更好的方法来避免这种情况,而不是使用:if\uuuu name\uuuuu=='\uuuuuuu'main\uuuuuu':?你知道吗

(也许每次tot迭代都会转储内存或者类似的东西?)你知道吗

下面是我的代码:

a = [[('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo', 4)],[('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo', 4)],[('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo', 4)],[('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo', 4)]]

def hydra_gecko(file_name, initial_letter, final_letter, process_number):
    # url and proxy details here
    response = requests.get(url, headers=header_switcher(), proxies={'http': proxy, 'https': proxy}, timeout=(1, 3))
    # parse html and gather data


for multi_arguments in a:
if __name__ == '__main__':
    with Pool(5) as p:
        print(p.starmap_async(hydra_gecko, multi_arguments))
        p.close()
        p.join()

有没有更好的办法? 是否有一个代码在每次tot迭代时转储内存,或者类似的代码比上面的代码更好? 谢谢


Tags: 内存代码nametxt代理abadac
1条回答
网友
1楼 · 发布于 2024-04-25 14:29:16

您正在为每个multi_arguments创建一个新池。那是浪费资源。如果工作进程的总数超过了CPU的核心数,那么工作进程将争夺CPU资源,甚至内存,从而减慢整个进程的速度。你知道吗

池的全部目的是处理比辅助函数更多的项。你知道吗

请尝试以下操作(使用单个池):

a = [
  ('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3),
  ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2),
  ('ae.txt', 'ae', 'aeo', 4), ('ab.txt', 'ab', 'abo', 1),
  ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5),
  ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo',4)
  ('ab.txt', 'ab', 'abo', 1), ('ac.txt', 'ac', 'aco', 3),
  ('acz.txt', 'acz', 'ac o', 5), ('ad.txt', 'ad', 'ado', 2),
  ('ae.txt', 'ae', 'aeo', 4), ('ab.txt', 'ab', 'abo', 1),
  ('ac.txt', 'ac', 'aco', 3), ('acz.txt', 'acz', 'ac o', 5),
  ('ad.txt', 'ad', 'ado', 2), ('ae.txt', 'ae', 'aeo', 4)
]

def hydra_gecko(item):
    file_name, initial_letter, final_letter, process_number = item
    # url and proxy details here
    response = requests.get(
      url, headers=header_switcher(),
      proxies={'http': proxy, 'https': proxy},
      timeout=(1, 3)
    )
    # parse html and gather data, return result.
    return response.status_code

if __name__ == '__main__':
# Do **not** choose a number of workers. The default usually works fine.
# If you are worried about memory leaks, set maxtasksperchild
# to refresh the worker process after a certain number of tasks.
with Pool(maxtasksperchild=4) as p:
    for result in p.imap_unordered(hydra_gecko, a):
        print(result)

相关问题 更多 >