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中执行此操作?
4 个解决方案
#1
35
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.
但是,请查看检查模块,因为它确实是您要对框架执行的最常见操作。
#2
22
I use these little guys for debugging and logging:
我用这些小家伙进行调试和记录:
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 )
#3
22
The best answer would be to use the inspect module; not a private function in sys
.
最好的答案是使用检查模块;不是sys中的私有函数。
import inspect
current_frame = inspect.currentframe()
#4
-3
See the dir function.
请参阅dir函数。
sorry - not actually relevant to the frame, but still useful!
对不起 - 实际上与框架无关,但仍然有用!
#1
35
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.
但是,请查看检查模块,因为它确实是您要对框架执行的最常见操作。
#2
22
I use these little guys for debugging and logging:
我用这些小家伙进行调试和记录:
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 )
#3
22
The best answer would be to use the inspect module; not a private function in sys
.
最好的答案是使用检查模块;不是sys中的私有函数。
import inspect
current_frame = inspect.currentframe()
#4
-3
See the dir function.
请参阅dir函数。
sorry - not actually relevant to the frame, but still useful!
对不起 - 实际上与框架无关,但仍然有用!