如何在python中跟踪内置函数 [英] How to trace builtin functions in python

查看:59
本文介绍了如何在python中跟踪内置函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在文件上下文管理器中调用 __ enter __ __ exit __ 方法.

I am trying to understand how __enter__ and __exit__ methods are called in file context manager.

with open("test.txt") as fp:
  fp.read()

我在pdb中尝试了 step 命令-而不是去定义函数 open ,它只是执行它并移至下一行.

I have tried step command in pdb - instead of going to definition of the function open, it just executes it and moves on to the next line.

我也尝试过使用 sys.settrace(),但是即使它没有捕获函数调用 open __ enter __ __ exit __ 在任何事件中.

I tried using sys.settrace() too, but even it is not capturing the function calls open, __enter__, and __exit__ in any of the events.

当然,这适用于从其他模块和同一模块中导入的功能.我以为这应该以类似的方式对这些内置函数起作用.我找不到任何指向此的文档.可以介入或跟踪内置函数的执行吗?

Of course, this works for functions imported from other modules and in the same module. I was assuming this should work for these builtin functions out of the box in a similar manner. I could not find any documentation pointing to this. Is it possible to step into or trace execution of builtin functions?

使用Python 2.7.

Using Python 2.7.

推荐答案

尝试使用 sys.settrace 跟踪内置函数时:

Try using sys.setprofile instead of sys.settrace when tracing builtin functions:

系统的配置文件函数的调用方式与系统的跟踪功能类似(请参阅settrace()),但是会使用不同的事件来调用,例如,不会为每一行已执行的代码调用它(仅在调用和返回时,但即使设置了异常,也会报告返回事件)

The system’s profile function is called similarly to the system’s trace function (see settrace()), but it is called with different events, for example it isn’t called for each executed line of code (only on call and return, but the return event is reported even when an exception has been set)

除了事件"call"和"return"之外, setprofile 还提供了"c_call"和"c_return",它们表示从内置函数进行调用和返回.

Besides the events "call" and "return", setprofile also offers "c_call" and "c_return" which refer to calling and returning from a builtin function.

请注意其他两个参数 frame arg 的含义已更改:
如果 event 等于"c_call"或"c_return",则 frame 是调用内置函数的外部框架,因此 frame.f_code.co_name 不是内置函数的名称,而是调用它的python函数的名称.相反, arg 是C函数对象,而不是返回值.

Be aware of the altered meaning of the other two arguments frame and arg:
If event equals "c_call" or "c_return", frame is the outer frame from where the builtin function was called, so frame.f_code.co_name will not be the name of the builtin function but the name of the python function calling it. Instead, arg is the C function object, not the return value.

所以回答您的问题:

是否可以介入或跟踪内置函数的执行?

Is it possible to step into or trace execution of builtin functions?

是的,可以跟踪内置函数的调用/返回,但是,您不能单步执行.我猜您之所以在调试器中什至看不到c_call/c_return的原因是因为它使用的是settrace而不是setprofile.

Yes, it is possible to trace the call/return of builtin functions, however, you are not able to step into one. I guess the reason why you don't even see the c_call/c_return with your debugger is because it uses settrace and not setprofile.

这篇关于如何在python中跟踪内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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