如何模仿C#的#define功能,可选择在Python中打印调试输出?

时间:2014-11-21 21:32:05

标签: python c debugging preprocessor-directive

我有一个巨大的python代码,其中包含许多用于调试的打印语句。我希望能够一次性启用或禁用它们,而无需仔细研究数百个printf并每次都对它们进行评论。

在C中,可以使用#define使用#ifdef来评论代码中不需要的部分 -

#define debug
#ifdef debug
    printf("Debug on")
#endif

如果我不想处于调试模式,我可以简单地注释#define debug,我的print语句都不会编译。

如何在Python中完成此功能?

3 个答案:

答案 0 :(得分:4)

Python没有与C的宏直接等价,因为它没有预处理器,也没有像C那样区分编译时和运行时。

然而,一个简单的解决方案是将print行放在if语句中:

if False:
    print(...)
    print(...)
    print(...)
    ...

然后,您只需将False更改为True即可执行这些操作。


同样,你可以这样做:

DEBUG = False

if DEBUG:
    print(...)
    print(...)
    print(...)
    ...

然后将DEBUG名称更改为True


第三个(可能是最好的)选项是使用Python的内置__debug__ flag

if __debug__:
    print(...)
    print(...)
    print(...)
    ...

__debug__是一个常量,如None,如果在没有True选项的情况下启动Python(它处于调试模式),则设置为-O。否则,如果设置了-O选项(我们处于优化/生产模式),__debug__将设置为False,并且解释器将完全忽略使用它的代码,以便没有性能损失。

答案 1 :(得分:2)

您应该查看Python日志库:

https://docs.python.org/2/library/logging.html

答案 2 :(得分:1)

使用python标准库logging模块。这是一个easier-to-read tutorial on the logging module

您可以像这样设置给定代码运行的调试级别(有关详细信息,请参阅this section):

import logging
# if you want you can also set filename="logfile.txt" to write to file
logging.basicConfig(level=logging.DEBUG) # there are other options like logging.INFO
x = 42.31415
# Run your program here....
logging.debug("x is now" + str(x))

所以你甚至可以在命令行传递调试级别,如果你这样选择,比如说做

--loggingLevel=DEBUG