I want to add a verbose option to my python script but I'm not sure the best way to go about this. My main() function calls a parse_cmdline() function then a process() function. I want to create a function for my verbose option. I'm not sure where I should define my verbose function. Will I have to pass the verbose option from my parse_cmdline() to my process() function? I am looking for the best way to go about this.
You basically need a logging module to filter out output depending on the required verbosity.
That is, every output message gets given a severity level (like debug
or warning
), and you can then decide what is the minimum severity level for the messages to be displayed.
You just use the parsed the arguments to decide the required severity level (Basically, the higher the minimum severity level, the less verbose the program is).
I can only recommend the awesome logbook
module. Using a handler
whose log level
is set to the minimum required severity you require will easily solve your issue (e.g. Display only notice
and higher...).
You will then have to replace calls to print
in your script with logging calls logbook.debug
, logbook.info
, and so on.
There are a lot of more advanced features in logbook
, feel free to look around the documentation.
Please be aware that, by default, logbook
registers a StderrHandler
and pushes it to the application, you can easily undo that with logbook.default_handler.pop_application()
.
There are other solutions, as suggested by the documentation.