Fly*_*ing 3 python sockets exit python-3.x
我想知道是否:
with open_the_socket() as s:
use s
Run Code Online (Sandbox Code Playgroud)
按预期工作。我在另一个问题上读到,只要套接字的退出函数调用关闭,它就会起作用。据说 2.7 没有,但我正在使用 3.4,我只是想知道。
这是Python 3.4.0的socket.py的片段:
def __exit__(self, *args):
if not self._closed:
self.close()
Run Code Online (Sandbox Code Playgroud)
因此,它关闭套接字(与Python 2.7.10相反,其中套接字对象没有__exit__方法)。
有关上下文管理器的更多详细信息,请检查[Python 3.4.Docs]:数据模型 - 使用语句上下文管理器。
示例测试代码:
Run Code Online (Sandbox Code Playgroud)>>> >>> 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.looking(thing)强制关闭套接字(感谢 @glglgl 的提示):
>>>
>>> import socket
>>>
>>>
>>> s = None
>>>
>>> with socket.create_connection(("www.example.com", 80)) as s:
... print(s._closed)
...
False
>>>
>>> print(s._closed)
True
Run Code Online (Sandbox Code Playgroud)