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

后端 未结 9 1205
渐次进展
渐次进展 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: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.

提交回复
热议问题