python——上下文切换
参考:https://docs.python.org/3.5/library/contextlib.html
import contextlib @contextlib.contextmanager def foo(): print(1) yield print(3) with foo(): print(2) ''' 说明: 1. @contextlib.contextmanager使用该装饰器之后可以使用with方法调用foo函数; 2. 执行foo函数,遇到yield跳出函数执行with方法内的代码print(2); 3. 执行完with代码,跳回函数继续执行print(3) '''
使用场景:需要自动关闭的情况,使用with。比如文件操作和socket操作。
import contextlib import socket @contextlib.contextmanager def context_socket(host,port): sk = socket.socket() sk.bind((host,port)) sk.listen(5) try: yield sk #将sk返回给sock finally: sk.close() with context_socket('127.0.0.1',8888) as sock: #将sk返回给sock print(sock)

浙公网安备 33010602011771号