urllib.request.urlretrieve在python 3

时间:2017-02-27 18:19:43

标签: python-3.x urllib

参考python 3中的以下代码从url下载图像 -

import urllib.request
try:
    print('entering urlretrieve')
    # If connection failed after entering the function urllib.request.urlretrieve()
    urllib.request.urlretrieve('img_url','temp_location')
    print('exited urlretrieve')
except:
    print('connection problem')
print('program ended')

现在,问题是如果连接在urllib.request.urlretrieve()内失败,那么程序只是等待并且什么都不做

在这种情况下的输出是 -

  

进入urlretrieve。

但是,要求是终止打印 -

  

连接问题

当此函数内发生异常时。

请帮助!

1 个答案:

答案 0 :(得分:0)

您可以在代码顶部使用此行

socket.setdefaulttimeout(15)

如果您想了解更多信息,请查看this answer