在 Python 中,如何获取当前帧?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1140194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, how do I obtain the current frame?
提问by chollida
In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
在其他语言中,我可以通过反射 api 获取当前帧,以确定哪些变量是我当前所在范围的本地变量。
Is there a way to do this in Python?
有没有办法在 Python 中做到这一点?
回答by David Raznick
import sys
sys._getframe(number)
The number being 0 for the current frame and 1 for the frame up and so on up.
当前帧的数字为 0,向上的帧为 1,依此类推。
The best introduction I have found to frames in python is here
我在 python 中找到的最好的框架介绍在这里
However, look at the inspect module as it does most common things you want to do with frames.
但是,请查看检查模块,因为它可以执行您想要对框架执行的最常见的操作。
回答by notbad.jpeg
回答by Kevin Little
I use these little guys for debugging and logging:
我使用这些小家伙进行调试和日志记录:
import os
import sys
def LINE( back = 0 ):
return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
frame = sys._getframe( back + 1 )
return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
frame.f_lineno, frame.f_code.co_name )