python - 没有更好的方式来获取表达式在调试功能 [英] python - is there no better way to get the expression in a debug function

查看:210
本文介绍了python - 没有更好的方式来获取表达式在调试功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c代码中我经常使用printf调试宏,如

  #define DPRINT_INT(i)fprintf(stderr,%s具有%i在行%i,#i,i,__LINE__上的值%i 

然后我可以做如
DPRINT_INT(height)
这样的东西,它将打印变量或
DPRINT_INT(from_cm_to_inch(get_average(heights)))
,它将打印出整个为了这个名字,表达式。



为了做到这一点,python,因为python没有c样的宏



我传递一个字符串并使用检查来获取调用函数环境调用eval。
但我不喜欢传递字符串,它的丑陋和容易忘记(我有它的检查类型,并调用异常,如果它被传递一个非字符串),并不适用于ide。 p>

没有办法从调试函数的python代码中提取变量名和表达式?是在吗?

解决方案

在Python中,我们倾向于编写我们可以 unittest 和/或导入到REPL并在必要时将其驱动到那里。



如果您可以对您的功能进行单元测试,您可以证明其对于任何给定输入的行为。但是,如果您必须编写调试语句,则应使用 debug() logging 模块。



例如:



 #!/ usr / bin / env python 

import logging
import inspect

def buggy_fn():
d = 42;
如果d!= 69:
logging.debug('%s(%d)):%s不是我们预期的[%s]',
inspect.currentframe()。 f_back.f_code.co_filename,
inspect.currentframe()。f_back.f_lineno,
'd',
repr(d),


如果__name__ =='__main__':
logging.basicConfig(level = logging.DEBUG)
buggy_fn()



将输出...



  DEBUG:root:./ buggy.py(19): d不是我们的预期。 [42] 

检查 ,可以帮助您在需要的时间内。


in c code I frequently use printf debugging macros like

#define DPRINT_INT(i) fprintf(stderr,"%s has the value %i at line %i", #i,i, __LINE__)

and then i can do things like DPRINT_INT(height) where it will print the variable or things like DPRINT_INT(from_cm_to_inch(get_average(heights))) and it will print out the whole expression for the name.

To do this for python, since python doesn't have c-like macros

I pass a string and use inspect to get the calling functions environment to call eval with. But I don't like passing strings, its ugly and easy to forget(I have it check type and call an exception if it gets passed a non string) and doesn't work as well with the ide.

There isn't any way to extract the variable names and expressions from the python code for the debug function? is there?

解决方案

In Python we tend to write modules that we can unittest and / or import into the REPL and drive them there if necessary.

If you can unit-test your functions, you can prove their behaviour for any given input. However, if you must write debug statements, you should use debug() from the standard logging module.

For example:

#!/usr/bin/env python

import logging
import inspect

def buggy_fn():
    d = 42;
    if d != 69:
        logging.debug('%s(%d): %s is not what we expected. [%s]',
                inspect.currentframe().f_back.f_code.co_filename,
                inspect.currentframe().f_back.f_lineno,
                'd',
                repr(d),
                )

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    buggy_fn()

Will output...

DEBUG:root:./buggy.py(19): d is not what we expected. [42]

There's a wealth of useful stuff in inspect that may help you out in your hour of need.

这篇关于python - 没有更好的方式来获取表达式在调试功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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