sys中有个属性_getframe,它的官方解释如下:
def _getframe(depth=None): # real signature unknown; restored from __doc__
"""
_getframe([depth]) -> frameobject
Return a frame object from the call stack. If optional integer depth is
given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueError is raised. The default
for depth is zero, returning the frame at the top of the call stack.
This function should be used for internal and specialized
purposes only.
"""
pass
大概意思是可以定位到调用函数的那一层堆栈,也就是层级,比如函数调用过程的层级。用来根据深度depth来定位到对象的调用位置。
举个例子:
# test.py
0 def again():
1 _get_frame = getattr(sys, '_getframe')
2 frame = _get_frame(3)
3 filename = os.path.split(frame.f_code.co_filename)[1]
4