在python中如何在IOError期间自动重新连接

在python中如何在IOError期间自动重新连接,python,Python,我正在使用python获取链接。突然,我失去了连接,显示了一个错误,如下所示 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')

我正在使用python获取链接。突然,我失去了连接,显示了一个错误,如下所示

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')

您只需使用
try

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

您只需使用
try

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

如果加载您的图形时出现实际问题,那么,一个简单的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

为了防止意外问题,我有时也会在失败调用后的成功尝试之间使用延迟(time.sleep)

如果加载图形时出现实际问题,那么简单的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

为了防止意外问题,我有时也会在失败的调用后的成功尝试之间使用延迟(time.sleep)

如果您显示代码的相关部分,这会有所帮助……我已经更新了,上面的示例就是这样。你愿意帮助我吗?如果你展示了你代码的相关部分,那会有帮助的……我已经用上面的例子更新了。你愿意帮我吗?