Check if internet access is available in Python

I have an application that makes an HTTP GET request to a specific URL on the Internet. But when the network is disconnected (say, no public Wi-Fi - or my Internet service provider is down, or something like that), I get the following trace in urllib2.urlopen:

70, in get
    u = urllib2.urlopen(req)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 409, in _open
    '_open', req)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 1161, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 1136, in do_open
    raise URLError(err)
URLError: <urlopen error [Errno 8] nodename nor servname provided, or not known>

I want to print a friendly error so that the user tells him that his network may not be available instead of this unfriendly "nodename or servname provided" message. Of course, I can catch URLError, but it will catch every URL error, and not just one that is related to network downtime.

, " example.com, , ". ? ( , DNS urllib2.urlopen, ? , "" ?)

+3
3

try/except, , .

try:
   u = urllib2.urlopen(req)
except HTTPError as e:
   #inform them of the specific error here (based off the error code)
except URLError as e:
   #inform them of the specific error here
except Exception as e:
   #inform them that a general error has occurred 
+8

urllib2 - , URLError HTTPError , .

+1

How about catch URLErrorand then attribute testing reason? If the reason is not what interests you, repeat the roll URLErrorand process it somewhere else.

Alternatively you can try httplib2 . An exception would ServerNotFoundErrorprobably fit your needs.

+1
source

Source: https://habr.com/ru/post/1742553/


All Articles