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?
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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With