你能将这个C++调试宏翻译成Python吗?
我在用C++开发的时候,会用到一个非常有用的宏:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
你能帮我把这个想法用Python实现吗?我不知道如何用Python函数来实现#a...
6 个回答
3
import sys
def DD(expr):
frame = sys._getframe(1)
print '%s = %s' % (expr, repr(eval(expr, frame.f_globals, frame.f_locals)))
GLOBAL_VAR = 10
def test():
local_var = 20
DD('GLOBAL_VAR + local_var')
>>> test()
GLOBAL_VAR + local_var = 30
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
7
正如@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')
结果是:
a: 5
6
你可以查看堆栈跟踪并“解析”它。因为你知道你的函数名称(在这个例子中是 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()
输出
a = 4