import socket import contextlib @contextlib.contextmanager def 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 connect sock auto close ============ finally close
时间: 2024-10-27 01:41:30