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
另一个示例:
__author__ = 'alex' #coding:utf-8 import contextlib @contextlib.contextmanager def worker_state(state_list, worker_thread): """ 用于记录线程中正在等待的线程数 """ state_list.append(worker_thread) try: print ("begin yield") yield print ("stop yield") finally: print ("begin finally") state_list.remove(worker_thread) print ("stop finally") free_list = [] current_list = "alex" with worker_state(free_list,current_list): print (123) print (456)
执行结果:
begin yield 123 456 stop yield begin finally stop finally