你能把这个调试宏从C ++翻译成python吗? [英] Can you translate this debugging macro from C++ to python?

查看:178
本文介绍了你能把这个调试宏从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中实现同样的想法吗?我不知道如何使用python函数实现 #a ...

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吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆