Reputation: 1249
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.
Upvotes: 1
Views: 2680
Reputation: 55293
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.
Upvotes: 2
Reputation: 6388
Parse your options with argparser
and either pass them around or put them in a global
Note that you only have to use the global
keyword when you want to assign to some name in the global scope, not when you just want yo read the value.
Upvotes: 0
Reputation: 16327
Take a look at plac
. It's an awesome package for commandline parsing, much more inituitive than the built-in argparse
, in my opinion.
Upvotes: 0