我想知道这个东西是否:
with open_the_socket() as s:
use s
功能正常。我在另一个问题中看到,只要套接字的退出函数调用了close,它就可以工作。据说2.7没有这样做,但我正在使用3.4,我想知道。
我想知道这个东西是否:
with open_the_socket() as s:
use s
功能正常。我在另一个问题中看到,只要套接字的退出函数调用了close,它就可以工作。据说2.7没有这样做,但我正在使用3.4,我想知道。
def __exit__(self, *args):
if not self._closed:
self.close()
>>>
>>> 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
__exit__
方法时,OP可以轻松使用with contextlib.closing(open_the_socket()) as s:
。 - glglgl