代码之家  ›  专栏  ›  技术社区  ›  Sridhar Ratnakumar

检查Python是否不能访问internet

  •  3
  • Sridhar Ratnakumar  · 技术社区  · 14 年前

    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>
    

    URLError ,但那会很吸引人 url错误,不仅仅是与网络停机有关的错误。

    我不是一个纯粹主义者,所以即使是一个错误消息,如“The server example.com cannot be access;要么是服务器确实有问题,要么是你的网络连接断了。如何有选择地捕捉这些错误(首先,如果DNS解析在 urllib2.urlopen文件

    3 回复  |  直到 14 年前
        1
  •  8
  •   Sridhar Ratnakumar    13 年前

    您应该将请求包装在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 
    
        2
  •  1
  •   Amal Sirisena    14 年前

    urllib2 - The Missing Manual 关于如何处理urleror和HTTPError异常以及如何区分导致它们的条件,有一个很好的章节。

        3
  •  1
  •   splicer    14 年前

    抓人怎么样 URLError reason 属性?如果原因不是你感兴趣的,重新抛出 在别的地方处理。

    或者,你可以试试 httplib2 . 它 ServerNotFoundError 例外情况可能适合你的需要。