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

后端 未结 9 1240
渐次进展
渐次进展 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 11:04

    There could be a global variable, likely set with argparse from sys.argv, that stands for whether the program should be verbose or not. Then a decorator could be written such that if verbosity was on, then the standard input would be diverted into the null device as long as the function were to run:

    import os
    from contextlib import redirect_stdout
    verbose = False
    
    def louder(f):
        def loud_f(*args, **kwargs):
            if not verbose:
                with open(os.devnull, 'w') as void:
                    with redirect_stdout(void):
                        return f(*args, **kwargs)
            return f(*args, **kwargs)
        return loud_f
    
    @louder
    def foo(s):
        print(s*3)
    
    foo("bar")
    

    This answer is inspired by this code; actually, I was going to just use it as a module in my program, but I got errors I couldn't understand, so I adapted a portion of it.

    The downside of this solution is that verbosity is binary, unlike with logging, which allows for finer-tuning of how verbose the program can be. Also, all print calls are diverted, which might be unwanted for.

提交回复
热议问题