How to simulate C # define functionality for optional debug output in Python?

I have a great python code with many print statements useful for debugging. I want to be able to enable or disable them at a time without looking at hundreds printfand commenting on them each time.

In C, a #definecan be used to comment on unnecessary parts of code, using #ifdef, like this -

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

If I don't want to be in debug mode, I can just comment on #define debug and none of my statements printwill compile.

How can this function be executed in Python?

+4
source share
3

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, , .

+4

python logging. .

, (. ):

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))

So, you can even pass the debug level to the command line, if you decide so, say something like

--loggingLevel=DEBUG
+1
source

All Articles