Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 349
thornomad Avatar asked Nov 29 '09 15:11

thornomad


People also ask

How do you implement a Python script?

Using the python Command To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do you implement verbosity in Python?

verbose: log. basicConfig(format="%(levelname)s: %(message)s", level=log. DEBUG) log.info("Verbose output.") else: log. basicConfig(format="%(levelname)s: %(message)s") log.info("This should be verbose.") log.

Which option is used to execute Python program?

The most basic and easy way to run a Python script is by using the python command. You need to open a command line and type the word python followed by the path to your script file, like this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard and that's it.

How do you insert verbose?

Enable verbose status messages by using Registry EditorClick Start > Run. In the Open box, type regedit, and then click OK. On the Edit menu, point to New, and then click DWORD Value.


1 Answers

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
like image 92
Stephan202 Avatar answered Sep 25 '22 07:09

Stephan202