Python3:资源警告未关闭

Python3: ResourceWarning Unclosed

我有一个在 Python 中编码的 Reddit 机器人,有时我会收到以下错误:

sys:1: ResourceWarning: unclosed ssl.SSLSocket fd=4, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('192.168.1.113', 55513), raddr=('198.41.209.140', 443)>

192.168.1.113 是我的本地 IP,198.41.209.140 显然是 CloudFlare 的 IP

我有时也会收到以下错误,这让我认为问题与 SSL 有关?

Error EOF occurred in violation of protocol (_ssl.c:598)

我该如何解决这个问题?

编辑:如何查看我的代码的哪一部分导致了这个问题?我的 try/except 中有一个例外,将所有例外打印为:

except Exception as e:
    print("Login/API Error", e)

但是我得到的所有错误都没有这个,这意味着它不是例外?

我没有在自己的代码中使用过套接字,所以下面是基于我的一般Python知识。

套接字文档没有说 socket.socket 实例是上下文管理器,但 class 具有必需的 __enter____exit__ 方法。两者都是标准的、最小的实现。您可能希望 subclass 套接字或 SSLSocket 在 __exit__ 中做更多事情,例如打印您的替代品以进行回溯。但首先,您需要查看完整的回溯。 Subclass SSLSocket 继承了这两种方法。由于 SSLSocket "wraps" 是套接字,显然有两个对象需要关注。因此,对于代码的顶层结构,我将从以下内容(显然未经测试)开始:

<preliminary code>
with socket.socket(...) as sock  # or other socket-returning function
  <more preparation>
  with ssl.wrap_socket(sock, ...) as SSLsock # or the context function
    <use SSLsock to communicate>

您收到的错误消息应该带有 SSLEOFError 前缀。是吗?文档说 "A subclass of SSLError raised when the SSL connection has been terminated abruptly. Generally, you shouldn’t try to reuse the underlying transport when this error is encountered." 这绝对是一个例外。

>>> issubclass(ssl.SSLEOFError, Exception)
True

什么可能会导致 Cloudfare 终止连接 'abruptly'?协议处理中的错误; ssl.py 中的错误?您的机器人是否以某种方式违反了服务条款?

如果您无法在这里获得所需的所有答案,我会尝试 python-list,也可以在 news.gmane.org 上作为新闻组 gmane.comp.python.general 访问。它有具有网络经验的参与者。