Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to toggle python prints?

I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build. It's also imperative that it's as transparent as possible.

My solution to this in the C code of the engine is having the printf function inside a vararg macro, and defining that to do nothing in a release build.

This is my current solution:

DebugPrints = True
def PRINT (*args):
    global DebugPrints
    if DebugPrints:
        string = ""
        for arg in args:
            string += " " + str(arg)
        print string

It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.

I'm wondering if there is anything you can do to how the print keyword works?

like image 338
Nathan Ross Powell Avatar asked Apr 02 '09 11:04

Nathan Ross Powell


People also ask

How do you display print in Python?

Python print() FunctionThe print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

How do you stop print in Python?

If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.


2 Answers

I know an answer has already been marked as correct, but Python has a debug flag that provides a cleaner solution. You use it like this:

if __debug__:
    print "whoa"

If you invoke Python with -O or -OO (as you normally would for a release build), __debug__ is set to False. What's even better is that __debug__ is a special case for the interpreter; it will actually strip out that code when it writes the pyc/pyo files, making the resulting code smaller/faster. Note that you can't assign values to __debug__, so it's entirely based off those command-line arguments.

like image 60
DNS Avatar answered Oct 14 '22 00:10

DNS


The logging module is the "best" way.. although I quite often just use something simple like..

class MyLogger:
    def _displayMessage(self, message, level = None):
        # This can be modified easily
        if level is not None:
            print "[%s] %s" % (level, message
        else:
            print "[default] %s" % (message)

    def debug(self, message):
        self._displayMessage(message, level = "debug")
    def info(self, message):
        self._displayMessage(message, level = "info")

log = MyLogger()
log.info("test")
like image 37
dbr Avatar answered Oct 14 '22 01:10

dbr