Skip to main content
 首页 » 编程设计

python之线程内存使用量不断增加

2024年11月01日7yxwkf

我正在尝试访问网页并检查网站所有者是否允许与他联系..

这里是 http://pastebin.com/12rLXQaz

这是每个线程调用的函数:

def getpage(): 
    try: 
        curl = urls.pop(0) 
        print "working on " +str(curl) 
        thepage1 = requests.get(curl).text 
        global ctot 
        if "Contact Us" in thepage1: 
            slist.write("\n" +curl) 
            ctot = ctot + 1 
    except: 
        pass 
    finally: 
        if len(urls)>0 : 
            getpage()   

但问题是程序的内存不断增加.. (pythonw.exe)

当线程再次调用该函数时,条件为真。程序的内存应该至少保持在大致相同的水平。

对于包含大约 10 万个 URL 的列表,该程序占用的空间远远超过 3GB,并且还在增加......

请您参考如下方法:

你的程序是无缘无故递归的。递归意味着对于您获得的每个页面,您都会创建一组新变量,并且由于函数中的局部变量仍在引用这些变量,因为函数永远不会结束,垃圾收集永远不会起作用,它将继续永远吞噬内存。

阅读 while声明,这是您要在此处使用而不是递归的声明。

while len(urls)>0 : 
    try: 
        curl = urls.pop(0) 
        thepage1 = requests.get(curl).text 
        global ctot 
        if "Contact Us" in thepage1: 
            slist.write("\n" +curl) 
            ctot = ctot + 1 
    except: 
        pass