質問

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.

役に立ちましたか?

解決

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 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).

Logbook

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.

他のヒント

Have you looked into argh?

First import

import argh

Then you would use something like this to add the option

@argh.arg('--verbose', default=False, help='Be more verbose')

Take a look at plac. It's an awesome package for commandline parsing, much more inituitive than the built-in argparse, in my opinion.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top