TeAmEr
TeAmEr

Reputation: 4773

Python: have urllib skip failed connection

Using a Nokia N900 , I have a urllib.urlopen statement that I want to be skipped if the server is offline. (If it fails to connect > proceed to next line of code ) .

How should / could this be done in Python?

Upvotes: 1

Views: 2591

Answers (3)

unutbu
unutbu

Reputation: 880777

If you are using Python3, urllib.request.urlopen has a timeout parameter. You could use it like this:

import urllib.request as request
try:
    response = request.urlopen('http://google.com',timeout = 0.001)
    print(response)
except request.URLError as err:
    print('got here')
    # urllib.URLError: <urlopen error timed out>

timeout is measured in seconds. The ultra-short value above is just to demonstrate that it works. In real life you'd probably want to set it to a larger value, of course.

urlopen also raises a urllib.error.URLError (which is also accessible as request.URLError) if the url does not exist or if your network is down.

For Python2.6+, equivalent code can be found here.

Upvotes: 3

Velociraptors
Velociraptors

Reputation: 2030

According to the urllib documentation, it will raise IOError if the connection can't be made.

try:
    urllib.urlopen(url)
except IOError:
    # exception handling goes here if you want it
    pass
else:
    DoSomethingUseful()

Edit: As unutbu pointed out, urllib2 is more flexible. The Python documentation has a good tutorial on how to use it.

Upvotes: 3

Vladimir Lagunov
Vladimir Lagunov

Reputation: 1905

try:
    urllib.urlopen("http://fgsfds.fgsfds")
except IOError:
    pass

Upvotes: 3

Related Questions