标签:
1.上下文管理
import contextlib @contextlib.contextmanager def work_state(state_list,worker_thread): state_list.append(worker_thread) try: yield finally: state_list.remove(worker_thread) free_list=[] current_thread="alex" with work_state(free_list,current_thread): print(123) print(456) #以下为执行结果: 123 456
代码执行步骤
上下文用于需要 close()方法的模块
import contextlib import socket @contextlib.contextmanager def context_socket(host,port): sk=socket.socket() sk.bind((host,port)) sk.listen(5) try: yield sk finally: sk.close() with context_socket(‘127.0.0.1‘,8888) as sock: print(sock) #以下为执行结果: <socket.socket fd=224, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘127.0.0.1‘, 8888)>
标签:
原文地址:http://www.cnblogs.com/wudalang/p/5700242.html