在Python中socket __exit__会关闭吗?

问题描述 投票:0回答:1

我想知道是否:

with open_the_socket() as s:
    use s

按预期工作。我读到另一个问题,只要套接字的 exit 函数调用关闭,它就可以工作。据说 2.7 没有,但我正在使用 3.4,我只是想知道。

python sockets python-3.x exit
1个回答
5
投票

这是来自 Python 3.4.0socket.py 的片段:

def __exit__(self, *args):
    if not self._closed:
        self.close()

因此,它关闭套接字(与 Python 2.7.10 相反,其中 socket 对象没有 __exit__ 方法)。

检查 [Python 3.4.Docs]:数据模型 - 使用语句上下文管理器,了解有关上下文管理器的更多详细信息。

示例测试代码:

>>>
>>> import socket
>>>
>>>
>>> s = None
>>>
>>> with socket.create_connection(("www.example.com", 80)) as s:
...     print(s._closed)
...
False
>>>
>>> print(s._closed)
True
© www.soinside.com 2019 - 2024. All rights reserved.