SANCHIT NAGAR
SANCHIT NAGAR

Reputation: 11

urllib.request.urlretrieve hangs on failure in python 3

Referring to the following code in python 3 to download an image from 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')

Now, problem is if connection fails inside urllib.request.urlretrieve() then the program simply waits and do nothing

Output in this case is -

entering urlretrieve.

But, my requirement is to terminate printing -

connection problem

when exception occur inside this function.

Please Help!

Upvotes: 0

Views: 984

Answers (1)

Rasel Rahman
Rasel Rahman

Reputation: 47

You can use this line at the top of your code

socket.setdefaulttimeout(15)

Please check out this answer if you want to learn more

Upvotes: 1

Related Questions