2011-01-30 232 views
3

你好,我有問題。我使用機械化,python 2.7來連接一些站點(代碼現在不重要),我有站點列表,我現在連接到他們。當它發生的部位從我的名單並不存在,我得到錯誤:如何處理「getaddrinfo失敗」?

urllib2.URLError: [Errno 11004] getaddrinfo failed

我試圖這樣做是爲了處理:

   except mechanize.URLError, e: 
        result = str(e.reason) 

   except urllib2.URLError, e: 
        result = str(e.reason) 

甚至

   except Exception, e: 
        result = str(e) 

但它只是不想w掃。

如何解決這個問題?發生此錯誤時,我只想打印「連接失敗」之類的內容,並移至列表中的下一個地址。如何通過except捕獲此錯誤?

+3

什麼是「不想工作」是什麼意思?他們呼籲生病嗎?後追蹤。 – SilentGhost 2011-01-30 18:32:42

+0

@SilentGhost我認爲它的意思是「不捕捉」,但即使如此,「例外:除外」都可以工作。 Python的問題? – new123456 2011-01-30 18:34:59

回答

2

只是做

except urrlib2.URLError: 
    print "Connection failed" 
    continue # NOTE: This assumes this is in a loop. If not, substitute for return 

大多數Python庫告訴你在錯誤報告中的異常的類型,在這種情況下urllib2.URLError,所以這確實是你except什麼。

但是,如果except Exception:不適合您,那麼與用戶輸入錯誤的網址(假設這不是urllib2的錯誤)相比,您會遇到更嚴重的問題。

6

隨機猜測,但嘗試:

import socket 

try: 
    ... 
except socket.gaierror: 
    pass 

socket.gaierror"[Errno 11004] getaddrinfo failed"錯誤。

您可以輕鬆地找出異常,如果你這樣做

try: 
    ... 
except: 
    import sys 
    # prints `type(e), e` where `e` is the last exception 
    print sys.exc_info()[:2]