2011-12-17 21 views
0

我正在使用python獲取鏈接。突然我失去了連接並顯示如下錯誤。如何在python中的IOError期間自動重新連接

IOError: [Errno socket error] [Errno 110] Connection timed out 

如何重新連接相同的鏈接?

例如

import urllib 

a = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif' 
image = urllib.URLopener() 
image.retrieve(a,'1.jpg') 
+0

它會幫助你顯示了你的代碼的相關部分 – yurib 2011-12-17 12:41:47

+0

....我已經更新了上面的例子。 你想幫我嗎? – user1070579 2011-12-17 12:49:03

回答

2

您可以簡單地使用try..except語法:

import urllib 

a = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif' 
image = urllib.URLopener() 
while True: 
    try: 
     image.retrieve(a,'1.jpg') 
     break 
    except IOError: 
     pass 
1

如果有一個實際的問題加載你的身材,那麼,一個簡單的while循環將永遠不會結束,並且應用程序似乎會掛起。 爲了防止這種情況,我通常用一個計數器:

tries = 5 
while tries: 
    try: 
     image.retrieve(a,'1.jpg') 
     break 
    except IOError:  
     tries -= 1  #and maybe with 0.1-1 second rest here 
else: 
    warn_or_raise_something 

爲了防止道瞬態問題,我也嘗試succesive之間有時使用的延遲(time.sleep)失敗後,呼叫

相關問題