What's an easy way to implement a --quiet option in a python script
python
Solution
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
Problem
Am working on a command line python script - throughout the script, I have a lot of information I am `print`-ing to the terminal window so that I may follow along with what is happening. Using `OptionParser` I want to add a `--quiet` option so I can silence all the output. I am looking for a pythonic way to go about implementing this throughout the script so that I don't end up doing something like: ``` if not QUIET: # global variable set by OptionParser print " my output " ``` Am new to python and sure there is a better way. Ideas?