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.
Share
Logging
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
debugorwarning), 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).
Logbook
I can only recommend the awesome
logbookmodule. Using ahandlerwhose loglevelis set to the minimum required severity you require will easily solve your issue (e.g. Display onlynoticeand higher…).You will then have to replace calls to
printin your script with logging callslogbook.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,
logbookregisters aStderrHandlerand pushes it to the application, you can easily undo that withlogbook.default_handler.pop_application().There are other solutions, as suggested by the documentation.