如果您想要一个临时解决方案,它使用withhacks(特别是来自AnonymousBlocksInPython)的思想,那么它将起作用:
import sysimport inspectclass My_Context(object): def __init__(self,mode=0): """ if mode = 0, proceed as normal if mode = 1, do not execute block """ self.mode=mode def __enter__(self): if self.mode==1: print 'Met block-skipping criterion ...' # Do some magic sys.settrace(lambda *args, **keys: None) frame = inspect.currentframe(1) frame.f_trace = self.trace def trace(self, frame, event, arg): raise def __exit__(self, type, value, traceback): print 'Exiting context ...' return True
比较以下内容:
with My_Context(mode=1): print 'Executing block of pre ...'
与
with My_Context(mode=0): print 'Executing block of pre ... '
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)