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
有沒有一種方法,我可以處理所有這些異常,而不必每次都有太多的樣板代碼?
謝謝!
感謝您的回答,由C來(你很可能已經猜到通過使用0作爲虛假:)我慢慢學習如何編寫pythonic代碼。 – Kami 2011-03-22 17:14:24