How to implement the --verbose or -v option into a script?

后端 未结 9 1129
渐次进展
渐次进展 2020-12-12 10:35

I know the --verbose or -v from several tools and I\'d like to implement this into some of my own scripts and tools.

I thought of placing:<

相关标签:
9条回答
  • 2020-12-12 11:13

    Building and simplifying @kindall's answer, here's what I typically use:

    v_print = None
    def main()
        parser = argparse.ArgumentParser()
        parser.add_argument('-v', '--verbosity', action="count", 
                            help="increase output verbosity (e.g., -vv is more than -v)")
    
        args = parser.parse_args()
    
        if args.verbosity:
            def _v_print(*verb_args):
                if verb_args[0] > (3 - args.verbosity):
                    print verb_args[1]  
        else:
            _v_print = lambda *a: None  # do-nothing function
    
        global v_print
        v_print = _v_print
    
    if __name__ == '__main__':
        main()
    

    This then provides the following usage throughout your script:

    v_print(1, "INFO message")
    v_print(2, "WARN message")
    v_print(3, "ERROR message")
    

    And your script can be called like this:

    % python verbose-tester.py -v
    ERROR message
    
    % python verbose=tester.py -vv
    WARN message
    ERROR message
    
    % python verbose-tester.py -vvv
    INFO message
    WARN message
    ERROR message
    

    A couple notes:

    1. Your first argument is your error level, and the second is your message. It has the magic number of 3 that sets the upper bound for your logging, but I accept that as a compromise for simplicity.
    2. If you want v_print to work throughout your program, you have to do the junk with the global. It's no fun, but I challenge somebody to find a better way.
    0 讨论(0)
  • 2020-12-12 11:13

    It might be cleaner if you have a function, say called vprint, that checks the verbose flag for you. Then you just call your own vprint function any place you want optional verbosity.

    0 讨论(0)
  • 2020-12-12 11:14

    Use the logging module:

    import logging as log
    …
    args = p.parse_args()
    if args.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.warning("This is a warning.")
    log.error("This is an error.")
    

    All of these automatically go to stderr:

    % python myprogram.py
    WARNING: This is a warning.
    ERROR: This is an error.
    
    % python myprogram.py -v
    INFO: Verbose output.
    INFO: This should be verbose.
    WARNING: This is a warning.
    ERROR: This is an error.
    

    For more info, see the Python Docs and the tutorials.

    0 讨论(0)
提交回复
热议问题