twfx
twfx

Reputation: 1694

Python - hide debugging message in non-debug mode

I print out (m x n) table of values for debugging, however, I do not want the debug messages to be printed out in non-debugging mode. In C, it can be done with "#ifdef _DEBUG" in code and define _DEBUG in preprocessor definition. May I know what is equivalent way in Python?

Upvotes: 0

Views: 668

Answers (3)

Gajo
Gajo

Reputation: 66

Python has module called "logging" See this question: Using print statements only to debug

Or the basic tutorial: http://docs.python.org/2/howto/logging.html

Upvotes: 3

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

try this:

import settings
if settings.DEBUG:
    print testval

This prints testval if, and only if, DEBUG=True in settings.py

Upvotes: 0

Henry Keiter
Henry Keiter

Reputation: 17188

You could define a global variable someplace, if that's what you want. However, probably the cleaner and more standard way is to read a config file (easy because you can write a config file in plain Python) and define DEBUG in there. So you've got a config file that looks like this:

# program.cfg
# Other comments
# And maybe other configuration settings
DEBUG = True # Or False

And then in your code, you can either import your config file (if it's in a directory on the Python path and has a Python extension), or else you can execfile it.

cfg = {}
execfile('program.cfg', cfg) # Execute the config file in the new "cfg" namespace.
print cfg.get('DEBUG') # Access configuration settings like this.

Upvotes: 0

Related Questions