我希望能在另一个代码块的每一行运行一段代码。例如,想要在执行函数的下一行之前或之后评估全局变量。
例如,在下面的示例中,我尝试在
我正在尝试执行类似于此的操作:
我该如何执行这个操作?
编辑:以下是此线程目标的另一个示例:
在打印每个“bar”之前,我希望打印一个“hello”。主要目的是在执行代码的下一行之前能够执行另一个函数或测试任何类型的全局变量。想象一下,如果全局变量为True,则代码继续执行下一行;而如果全局变量为False,则停止函数执行。
编辑:某种程度上,我正在寻找一种将代码注入另一个代码块的工具。
编辑:感谢unutbu,我已经实现了这段代码:
例如,在下面的示例中,我尝试在
foo()
函数的每一行之前打印“hello”。我认为一个装饰器可以帮助我,但它需要一些内省特性来编辑foo()
函数的每一行并在其之前或之后添加我想要的内容。我正在尝试执行类似于此的操作:
>>> def foo():
... print 'bar'
... print 'barbar'
... print 'barbarbar'
>>> foo()
hello
bar
hello
barbar
hello
barbarbar
我该如何执行这个操作?
__code__
对象是否有帮助?我需要同时使用装饰器和内省吗?编辑:以下是此线程目标的另一个示例:
>>> def foo():
... for i in range(0,3):
... print 'bar'
>>> foo()
hello
bar
hello
bar
hello
bar
在打印每个“bar”之前,我希望打印一个“hello”。主要目的是在执行代码的下一行之前能够执行另一个函数或测试任何类型的全局变量。想象一下,如果全局变量为True,则代码继续执行下一行;而如果全局变量为False,则停止函数执行。
编辑:某种程度上,我正在寻找一种将代码注入另一个代码块的工具。
编辑:感谢unutbu,我已经实现了这段代码:
import sys
import time
import threading
class SetTrace(object):
"""
with SetTrace(monitor):
"""
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
# http://effbot.org/zone/python-with-statement.htm
# When __exit__ returns True, the exception is swallowed.
# When __exit__ returns False, the exception is reraised.
# This catches Sentinel, and lets other errors through
# return isinstance(exc_value, Exception)
def monitor(frame, event, arg):
if event == "line":
if not running:
raise Exception("global running is False, exiting")
return monitor
def isRunning(function):
def defaultBehavior(*args):
with SetTrace(monitor):
ret = function(*args)
return ret
return defaultBehavior
@isRunning
def foo():
while True:
time.sleep(1)
print 'bar'
global running
running = True
thread = threading.Thread(target = foo)
thread.start()
time.sleep(3)
running = False
monitor
中检查和更改局部变量和全局变量的值。 - unutbumonitor
内部终止foo
。 - unutbu