2011-03-22 106 views
1
網絡數據

我使用下面的代碼從一個網站的數據:如何可靠地處理在Python

time_out = 4 

def tryconnect(turl, timer=time_out, retries=10): 
    urlopener = None 
    sitefound = 1 
    tried = 0 
    while (sitefound != 0) and tried < retries: 
     try: 
      urlopener = urllib2.urlopen(turl, None, timer) 
      sitefound = 0 
     except urllib2.URLError: 
      tried += 1 
    if urlopener: return urlopener 
    else: return None 

[...]

urlopener = tryconnect('www.example.com') 
if not urlopener: 
    return None 
try: 
    for line in urlopener: 
     do stuff 
except httplib.IncompleteRead: 
    print 'incomplete' 
    return None 
except socket.timeout: 
    print 'socket' 
    return None 
return stuff 

有沒有一種方法,我可以處理所有這些異常,而不必每次都有太多的樣板代碼?

謝謝!

回答

6

可避免在第一功能過於一些樣板代碼:

time_out = 4 

def tryconnect(turl, timer=time_out, retries=10): 
    for tried in xrange(retries): 
     try: 
      return urllib2.urlopen(turl, None, timer) 
     except urllib2.URLError: 
      pass 
    return None 

,並在第二:

urlopener = tryconnect('www.example.com') 
if urlopener: 
    try: 
     for line in urlopener: 
      do stuff 
    except (httplib.IncompleteRead, socket.timeout), e: 
     print e 
     return None 
else: 
    return None 
+0

感謝您的回答,由C來(你很可能已經猜到通過使用0作爲虛假:)我慢慢學習如何編寫pythonic代碼。 – Kami 2011-03-22 17:14:24