检查是否无法在Python中访问Internet

Rei*_*ica 3 python networking exception urllib2

我有一个应用程序,它对Internet上的特定URL发出HTTP GET请求.但是当网络出现故障时(例如,没有公共wifi - 或者我的ISP出现故障,或者其他类似事情),我会得到以下回溯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>
Run Code Online (Sandbox Code Playgroud)

我想向用户打印一个友好的错误,告诉他他的网络可能已关闭,而不是这个不友好的"nodename或servname provided"错误消息.当然我可以捕获URLError,但这将捕获每个 URL错误,而不仅仅是与网络停机相关的错误.

我不是一个纯粹主义者,所以即使是一个错误消息,例如"无法访问服务器example.com;服务器确实存在问题或者您的网络连接已关闭"会很好.如何有选择地捕获此类错误?(首先,如果DNS解析失败urllib2.urlopen,可以合理地假设为网络不可访问性?如果是,我如何在except块中"捕获"它?)

Sha*_*son 8

您应该将请求包装在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 
Run Code Online (Sandbox Code Playgroud)

  • 但是`URLError`--作为基类 - 也会捕获`HTTPError`.我会自己编辑. (2认同)