sta*_*tti 2 c++ python debugging macros logging
在C++中开发时,我使用这个非常有用的宏:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
Run Code Online (Sandbox Code Playgroud)
你能帮我在python中实现同样的想法吗?我不知道如何#a
使用python函数实现...
正如@Andrea Spadaccini和@adirau指出的那样,不可能将值可靠地映射回Python变量名.您可以遍历所有名称空间,查找引用给定值的变量名称,但这会对系统产生影响,并且可能会返回错误的变量名称.
传递变量名称要容易得多:
import inspect
def pv(name):
frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
inspect.currentframe())[1]
# print(frame,filename,line_number,function_name,lines,index)
val=eval(name,frame.f_globals,frame.f_locals)
print('{0}: {1}'.format(name, val))
a=5
pv('a')
Run Code Online (Sandbox Code Playgroud)
收益率:
a: 5
Run Code Online (Sandbox Code Playgroud)
您可以检查堆栈跟踪并"解析"它.由于您知道函数的名称(在本例中为dd),因此很容易找到调用并提取变量的名称.
import inspect
import re
def dd(value):
calling_frame_record = inspect.stack()[1]
frame = inspect.getframeinfo(calling_frame_record[0])
m = re.search( "dd\((.+)\)", frame.code_context[0])
if m:
print "{0} = {1}".format(m.group(1), value)
def test():
a = 4
dd(a)
test()
Run Code Online (Sandbox Code Playgroud)
产量
a = 4
Run Code Online (Sandbox Code Playgroud)