【问题标题】:Using Boolean Flags in Python Click Library (command line arguments)在 Python Click 库中使用布尔标志(命令行参数)
【发布时间】:2019-02-04 10:40:08
【问题描述】:

我正在尝试为我的 Python 程序制作一个详细的标志。 目前,我正在这样做:

import click

#global variable
verboseFlag = False

#parse arguments
@click.command()
@click.option('--verbose', '-v', is_flag=True, help="Print more output.")
def log(verbose):
    global verboseFlag
    verboseFlag = True

def main():    
    log()        
    if verboseFlag:
         print("Verbose on!")

if __name__ == "__main__":
    main()

它永远不会打印“Verbose on!”即使我设置了“-v”参数。我的想法是 log 函数需要一个参数,但是我给它什么呢?另外,有没有办法在没有全局变量的情况下检查详细标志是否打开?

【问题讨论】:

    标签: python command-line-arguments python-click


    【解决方案1】:

    所以 click 不仅仅是一个命令行解析器。它还分派和处理命令。所以在你的例子中,log() 函数永远不会返回到main()。该框架的意图是装饰函数,即:log(),将完成所需的工作。

    代码:

    import click
    
    @click.command()
    @click.option('--verbose', '-v', is_flag=True, help="Print more output.")
    def log(verbose):
        click.echo("Verbose {}!".format('on' if verbose else 'off'))
    
    
    def main(*args):
        log(*args)
    

    测试代码:

    if __name__ == "__main__":
        commands = (
            '--verbose',
            '-v',
            '',
            '--help',
        )
    
        import sys, time
    
        time.sleep(1)
        print('Click Version: {}'.format(click.__version__))
        print('Python Version: {}'.format(sys.version))
        for cmd in commands:
            try:
                time.sleep(0.1)
                print('-----------')
                print('> ' + cmd)
                time.sleep(0.1)
                main(cmd.split())
    
            except BaseException as exc:
                if str(exc) != '0' and \
                        not isinstance(exc, (click.ClickException, SystemExit)):
                    raise
    

    结果:

    Click Version: 6.7
    Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
    -----------
    > --verbose
    Verbose on!
    -----------
    > -v
    Verbose on!
    -----------
    > 
    Verbose off!
    -----------
    > --help
    Usage: test.py [OPTIONS]
    
    Options:
      -v, --verbose  Print more output.
      --help         Show this message and exit.
    

    【讨论】:

    • 如何将实际的命令行参数/标志传递给 main?现在,像 'python3 tester.py --verbose' 这样的东西会给出与 'python3 tester.py' 相同的输出
    【解决方案2】:

    上面的答案很有帮助,但这是我最终使用的。我想我会分享,因为很多人都在看这个问题:

    @click.command()
    @click.option('--verbose', '-v', is_flag=True, help="Print more output.")
    def main(verbose):
        if verbose:
            # do something
    
    if __name__ == "__main__":
        # pylint: disable=no-value-for-parameter
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2018-11-04
      • 2011-06-27
      • 2023-04-03
      相关资源
      最近更新 更多