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?
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.
try:
urllib.urlopen("http://fgsfds.fgsfds")
except IOError:
pass
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.
精彩评论