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

时间:2021-03-16 23:16:32

I'm trying to make a verbose flag for my Python program. Currently, I'm doing this:

我正试图为我的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()

It'll never print "Verbose on!" even when I set the '-v' argument. My thoughts are that the log function needs a parameter, but what do I give it? Also, is there a way to check whether the verbose flag is on without global variables?

它永远不会打印“详细!”即使我设置'-v'参数。我的想法是日志功能需要一个参数,但我该怎么做呢?另外,有没有办法检查详细标志是否在没有全局变量的情况下打开?

1 个解决方案

#1


3  

So click is not simply a command line parser. It also dispatches and processes the commands. So in your example, the log() function never returns to main(). The intention of the framework is that the decorated function, ie: log(), will do the needed work.

所以click不仅仅是一个命令行解析器。它还会调度和处理命令。所以在你的例子中,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.

#1


3  

So click is not simply a command line parser. It also dispatches and processes the commands. So in your example, the log() function never returns to main(). The intention of the framework is that the decorated function, ie: log(), will do the needed work.

所以click不仅仅是一个命令行解析器。它还会调度和处理命令。所以在你的例子中,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.