使用Python中的布尔标志点击库(命令行参数)

问题描述 投票:8回答:2

我试图做一个详细的标志我的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()

它永远不会打印“上放牧!”甚至当我设置的“-v”的说法。我的想法是,对数函数需要一个参数,但我该怎么给呢?此外,有没有办法检查冗余标志是否是没有全局变量?

python command-line-arguments python-click
2个回答
12
投票

所以点击是不是一个简单的命令行分析器。它还调度和处理的命令。因此,在您的例子中,log()函数永远不会返回到main()。该框架的意图是装饰功能,即:log(),将做必要的工作。

Code:

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)

Test Code:

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

Results:

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.

3
投票

以上答案是有帮助的,但是这是我最终使用。我想,既然这么多人都在看这个问题,我会分享:

@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()
© www.soinside.com 2019 - 2024. All rights reserved.