从Python中调用名称空间获取本地人 [英] Get locals from calling namespace in Python
本文介绍了从Python中调用名称空间获取本地人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从一个调用函数中从Python检索局部变量.有什么办法吗?我意识到这不适用于大多数编程,但是我基本上是在构建调试器.例如:
I want to retrieve the local variables from Python from a called function. Is there any way to do this? I realize this isn't right for most programming, but I am basically building a debugger. For example:
def show_locals():
# put something in here that shows local_1.
local_1 = 123
show_locals() # I want this to show local_1.
我应该在show_locals
的正文中放入什么?如果必须修改调用语句,我可以做的最小修改是什么?
What do I put in the body of show_locals
? If I have to modify the calling statement, what is the minimal modification I can make?
注意:当show_locals
与其调用者所在的模块位于不同的模块中时,此方法必须起作用.
Note: this must work when show_locals
is in a different module to its caller.
推荐答案
If you're writing a debugger, you'll want to make heavy use of the inspect
module:
def show_callers_locals():
"""Print the local variables in the caller's frame."""
import inspect
frame = inspect.currentframe()
try:
print(frame.f_back.f_locals)
finally:
del frame
这篇关于从Python中调用名称空间获取本地人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文