我想在另一个代码块的每行之后运行一段代码。例如,希望能够在执行函数的下一行之前或之后评估全局变量。Python:在代码块的每一行添加代码例程
例如,下面我尝试在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
在这种新情况下,打印每个“条”之前,我想打印一个“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
非常感谢,这似乎是接近于此,你说得对,线程的主要目的不是调试,而是更多的是能够阻止正在执行的代码块在执行代码的每一行之前更改此函数将评估的另一个全局变量的值。 如果全局切换为false,则这将在代码的每一行内添加一个抢占点,然后如果切换为true,那么函数停止withtout到结束=>然后该函数执行该行并转到下一个一个 我是否明确了这一点? – afiah
是的,您可以检查*并从'monitor'内更改本地和全局值的值。 – unutbu
谢谢,但是我可以停止监视功能的当前执行吗?在这种情况下,停止执行foo()? (在某种程度上,我可以在我想要的时候添加返回行以完成我的功能?) – afiah