Python中的socket __exit__方法会关闭连接吗?

3

我想知道这个东西是否:

with open_the_socket() as s:
    use s

功能正常。我在另一个问题中看到,只要套接字的退出函数调用了close,它就可以工作。据说2.7没有这样做,但我正在使用3.4,我想知道。

1个回答

5
这是来自Python 3.4.0的socket.py的片段。
def __exit__(self, *args):
    if not self._closed:
        self.close()

所以,它关闭了套接字(与Python 2.7.10不同,在套接字对象中没有__exit__方法)。
请查看[Python 3.4.Docs]: 数据模型 - With语句上下文管理器以获取更多关于上下文管理器的详细信息。
示例测试代码:
>>>
>>> import socket
>>>
>>>
>>> s = None
>>>
>>> with socket.create_connection(("www.example.com", 80)) as s:
...     print(s._closed)
...
False
>>>
>>> print(s._closed)
True
在Python 2中,可以通过使用[Python 2.Docs]: contextlib.closing(thing)来强制关闭套接字(感谢@glglgl的提示)。
with contextlib.closing(open_the_socket()) as s:
    print(s)
    #use s

2
进一步扩展:当没有__exit__方法时,OP可以轻松使用with contextlib.closing(open_the_socket()) as s: - glglgl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接