Can you translate this debugging macro from C++ to python?(你能把这个调试宏从 C++ 翻译成 python 吗?)
问题描述
我在使用 C++ 开发时使用了这个非常有用的宏:
I use this very helpful macro when developing in C++:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
你能帮我在 python 中实现同样的想法吗?我不知道 #a 如何用 python 函数实现...
Could you help me implement the same idea in python? I don't know how the #a could be implemented with a python function...
推荐答案
您可以检查堆栈跟踪并解析"它.由于您知道函数的名称(在本例中为 dd),因此很容易找到调用并提取变量的名称.
You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable.
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
这篇关于你能把这个调试宏从 C++ 翻译成 python 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你能把这个调试宏从 C++ 翻译成 python 吗?
基础教程推荐
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
