socket.gaierror: [Errno -2] 名称或服务未知| Python

Posted

技术标签:

【中文标题】socket.gaierror: [Errno -2] 名称或服务未知| Python【英文标题】:socket.gaierror: [Errno -2] Name or service not known | Python 【发布时间】:2019-12-05 15:50:11 【问题描述】:

我已经关闭了我的互联网连接,并希望在代码中捕获它。我设置了超时限制,但它不起作用。我收到一大堆错误消息,我不明白。

谁能帮助理解这些错误消息的含义?

我的python代码(简化):

import requests
from requests.exceptions import Timeout

url = 'https://api.github.com'
try:
    resp = requests.get(url=url, timeout=7)
except Timeout:
    print('The request timed out')
else:
    entries = resp.json()
    print(entries)

错误信息:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 60, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 852, in _validate_conn
    conn.connect()
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 284, in connect
    conn = self._new_conn()
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7f1cea4779e8>: Failed to establish a new connection: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f1cea4779e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    resp = requests.get(url=url, timeout=7)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 72, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 520, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 630, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 508, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f1cea4779e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))

【问题讨论】:

【参考方案1】:

socket.gaierror: [Errno -2] Name or service not known 表示给定域 (api.github.com) 的名称解析失败。

名称解析(通常概念中的 DNS)可能由于各种原因而失败。由于您断开了互联网,原因很明显(Name or service not known)。

gai (GetAddressInfo) 实际上被glibc 用于执行名称解析,它是glibc 的一部分(您可以想象到socket 正在使用它)。也可以在/etc/gai.conf中实际配置。

【讨论】:

【参考方案2】:

一种可能的解决方案是使用OSError 捕获socket.gaioerror

文档信息:

socket.gaierror 异常

A subclass of OSError, this exception is raised for address-related errors by getaddrinfo() and getnameinfo(). The accompanying value is a pair (error, string) representing an error returned by a library call. string represents the description of error, as returned by the gai_strerror() C function. The numeric error value will match one of the EAI_* constants defined in this module.

链接: https://docs.python.org/3/library/socket.html#socket.gaierror

https://docs.python.org/3/library/exceptions.html#OSError

【讨论】:

以上是关于socket.gaierror: [Errno -2] 名称或服务未知| Python的主要内容,如果未能解决你的问题,请参考以下文章

cloudera安装报错 socket.gaierror: [Errno -2] Name or service not known

Python学习:socket.gaierror: [Errno -8]

Python 发送邮件 socket.gaierror: [Errno 11004] getaddrinfo failed

python telnet

通过http代理连接到FTP服务器

如何在将文件上传到s3时处理互联网不可用?