如何获取堆栈上函数的"program counter"?

How to get "program counter" for functions on the stack?

我想把我自己的 yield 版本卷起来,只是为了好玩。像这样:

class YieldJump(BaseException):
    ...
def Yield(returnVal):
    state = getCallerState()
    raise YieldJump(returnVal, state) 
class YieldWrap:
    def __init__(self, func, *vararg, **kwarg):
        # record function and argument
    def __call__(self):
        try: 
            ...
        except YieldJump as e:
            # record state and return value
def totalArbitraryFunction(...):
    ...
    Yield(i)
    ...
    Yield(i)
    ...
    Yield(i)
    ...
for i in YieldWrap(totalArbitraryFunction, arg1, arg2, ...):
    print(i)

为了 get/apply 调用者状态,我发现我可以使用 sysinspect 来获取 运行 堆栈上的 Frame 个对象(所以我可以对来电者做些什么)。从中我可以提取所有细节,包括 function 对象、存储的局部变量和函数所在的行号 运行。

但是行号不够详细,因为一行中可以嵌套函数调用。 有没有办法让return"address"强制python跳到那里?或者有没有办法 call/continue Frame/FrameInfo object?

框架的 f_lasti 是最接近它所拥有的 "program counter" 的东西,但这还不够。你不能从 Python 级代码设置 f_lasti,即使你可以(也许你使用的是 ctypes 的 "screw the rules" 按钮),你仍然不会'能够通过弄乱 f_lasti.

来暂停和恢复帧