跟踪Python函数时如何调用表达式? [英] How to get calling expression when tracing a Python function?

查看:432
本文介绍了跟踪Python函数时如何调用表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当内部跟踪功能调用函数调用时,是否可以以某种方式检索调用表达式?

When inside tracing function, debugging a function call, is it possible to somehow retrieve the calling expression?

我可以从追溯对象获取调用行号,但如果有是在该行上的几个函数调用(可能是相同的函数)(例如,在更大的表达式中作为子表达式),那么我如何知道这个调用来自哪里?即使从源代码行开始偏移,我也很高兴。

I can get calling line number from traceback object but if there are several function calls (possibly to the same function) on that line (eg. as subexpression in a bigger expression) then how could I learn where this call came from? I would be happy even with the offset from start of the source line.

traceback.tb_lasti 似乎给了更多大量的上下文(最后一个字节码的索引尝试) - 是否以某种方式将字节码连接到其确切的源范围?

traceback.tb_lasti seems to give more granual context (index of last bytecode tried) -- is it somehow possible to connect a bytecode to its exact source range?

编辑:只是为了澄清 - 我需要从调用源行提取特定(子)表达式(调用站点)。

Just to clarify -- I need to extract specific (sub)expression (the callsite) from the calling source line.

推荐答案

这就是我终于解决了这个问题:在原始程序中调用每个函数调用,并将其包含在与辅助函数的调用中,以及与原始调用的源位置相关的信息。实际上,我有兴趣控制程序中每个子表达式的评估,所以我包装了每个子表达式。

That's how I finally solved the problem: I instrumented each function call in the original program by wrapping it in a call to a helper function together with information about the source location of the original call. Actually I was interested in controlling the evaluation of each subexpression in the program, so I wrapped each subexpression.

更准确地说:当我有一个表达式 e 在原始程序中,它成为

More precisely: when I had an expression e in the original program, it became

_after(_before(location_info), e)

在仪器化程序中。帮助者定义如下:

in the instrumented program. The helpers were defined like this:

def _before(location_info):
    return location_info

def _after(location_info, value):
    return value

_before ,我知道它是要评估由 location_info 表示的位置的表达式(跟踪系统让我访问本地变量/参数,这就是我如何知道 location_info 的值)。当跟踪器报告调用 _after 时,我知道由 location_info 指示的expession刚刚被评估,并且值在

When tracer reported the call to _before, I knew that it's about to evaluate the expression at location represented by location_info (tracing system gives me access to local variables/parameters, that's how I got to know the value of location_info). When tracer reported the call to _after, I knew that the expession indicated by location_info was just evaluated and the value is in value.

我可以将这些执行事件处理写入这些帮助函数,并绕过跟踪系统总而言之,但是由于其他原因我也需要它,所以我用这些帮助者只是在跟踪系统中触发呼叫事件。

I could have written the execution "event handling" right into those helper functions and bypass the tracing system altogether, but I needed it for other reasons as well, so I used those helpers only for triggering a "call" event in tracing system.

结果可以在这里看到: http://thonny.org

The result can be seen here: http://thonny.org

这篇关于跟踪Python函数时如何调用表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆