What's an easy way to implement a --quiet option in a python script

You could use logging and assign those things that should not be printed if QUIET a different log level.

Edit: THC4K's answer shows an example of how to do this, assuming that all output should be silent if QUIET is set. Note that in Python 3 from __future__ import print_function is not necessary:

print = logging.info
logging.basicConfig(level=logging.WARNING if QUIET else logging.INFO,
                    format="%(message)s")

For for important output that should not be silenced by --quiet, define e.g. iprint:

iprint = logging.warning

can silence all the output by running it as python myscript.py > /dev/null

change the output streams in the script:

if QUIET:
    sys.stdout = open(os.devnull, 'a')
    sys.stderr = open(os.devnull, 'a')
print(something)

use a different print function

from __future__ import print_function
if QUIET:
    def print(*args):
        pass
print(something)

use logging and loglevels

from __future__ import print_function
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
print = logging.info
if QUIET:
    logging.basicConfig(level=logging.ERROR)

print(something)

Why don't you just modify your output function based on whether the program is in quiet mode, so you only do the check once?

if QUIET:
    def DoOutput(stuff):
        pass
else:
    def DoOutput(stuff):
        print(stuff)

Or, you could of course put the check for QUIET inside your output function:

def DoOutput(stuff):
    if QUIET:
        print(stuff)

The situation that you've described is actually one of the reasons that Python 3 has changed print from a keyword to an actual function: people's large projects were becoming very dependent on print being a keyword, and then when it came time to modify how output was recorded, it required a massive refactoring; whereas when print is a proper function, you can just redefine it, so that print(foo) would output to a log file, for instance. That's why it's better practice to wrap your output/logging in an actual function, rather than having print scattered about your script.

Tags:

Python