首页 > 代码库 > Python 上下文关系

Python 上下文关系

import socketimport contextlib@contextlib.contextmanagerdef con(host,port):    sk = socket.socket()    sk.bind((host,port))    sk.listen(5)    try:        print ("auto connect")        yield        print ("============")    finally:        print ("finally close")        sk.close()with con(127.0.0.1,8888) as sock:    print ("sock auto close")
执行结果:
auto connectsock auto close============finally close

 

Python 上下文关系