2009-11-28 57 views
0
links_list = char.getLinks(words) 
    for source_url in links_list: 
     try: 
      print 'Downloading URL: ' + source_url 
      urldict = hash_url(source_url) 
      source_url_short = urldict['url_short'] 
      source_url_hash = urldict['url_short_hash'] 
      if Url.objects.filter(source_url_short = source_url_short).count() == 0: 
        try: 
         htmlSource = getSource(source_url) 
        except: 
         htmlSource = '-' 
         print '\thtmlSource got an error...' 
       new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource) 
       new_u.save() 
       time.sleep(3) 
      else: 
       print '\tAlready in database' 
     except: 
      print '\tError with downloading URL..' 
      time.sleep(3) 
      pass 


def getSource(theurl, unicode = 1, moved = 0): 
    if moved == 1: 
     theurl = urllib2.urlopen(theurl).geturl() 
    urlReq = urllib2.Request(theurl) 
    urlReq.add_header('User-Agent',random.choice(agents)) 
    urlResponse = urllib2.urlopen(urlReq) 
    htmlSource = urlResponse.read() 
    htmlSource = htmlSource.decode('utf-8').encode('utf-8') 
    return htmlSource 

基本上這個代碼的作用是...它需要一個URL列表並下載它們,並將它們保存到數據庫中。就這樣。我的代碼是否泄漏內存(python)?

+1

是有一個原因你認爲你的代碼泄漏內存? – Jehiah 2009-11-28 03:09:42

+0

發生任何錯誤?或花費太多時間?雖然'htmlSource.decode('utf-8')。encode('utf-8')'這個技術很奇怪,它的解碼來自utf8並且同時編碼回utf8。 – YOU 2009-11-28 03:10:45

+0

沒有錯誤發生。但是,我的腳本隨機被「殺死」。之前有人建議這是內存泄漏,導致我的內存過載。 – TIMEX 2009-11-28 03:12:14

回答

1

也許你的過程中使用了太多的內存和服務器(可能是共享的主機)只是殺死它,因爲你耗盡你的內存配額。

這裏使用一個調用,吃了很多的記憶:

links_list = char.getLinks(words) 
for source_url in links_list: 
    ... 

看起來你可能會建設一個記憶整個名單,然後與項目合作。相反,使用迭代器可能會更好,其中一次只能檢索一個對象。但是這是一個猜測,因爲很難從你的代碼中知道char.getLinks是什麼

如果你在調試模式下使用Django,那麼內存的使用將會上升,正如Mark所建議的那樣。

0

如果你在Django中這樣做,確保DEBUG是False,否則它會緩存每個查詢。

See FAQ

0

檢查最簡單的方法是轉到任務管理器(在Windows上 - 或其他平臺上的等效項),並檢查Python進程的內存需求。如果保持不變,則不存在內存泄漏。如果不是這樣,你就有內存泄漏的地方,你需要調試

0

也許你應該得到一個工作服務器,如beanstalkd,並考慮一次只做一個。

作業服務器將重新請求失敗的作業服務器,從而完成剩下的工作。如果您需要(甚至在多臺計算機上),也可以同時運行多個客戶端。

設計簡單,易於理解和測試,更多的容錯,重試,更具可擴展性,等等