Python click包详解,简单易用的命令行传入参数

背景:

运行py脚本需要命令行传入参数

安装:

pip install click

使用方法:

import click

class DefaultHelp(click.Command):
    def __init__(self, *args, **kwargs):
        context_settings = kwargs.setdefault('context_settings', {})
        if 'help_option_names' not in context_settings:
            context_settings['help_option_names'] = ['-h', '--help']
        self.help_flag = context_settings['help_option_names'][0]
        super(DefaultHelp, self).__init__(*args, **kwargs)

    def parse_args(self, ctx, args):
        if not args:
            args = [self.help_flag]
        return super(DefaultHelp, self).parse_args(ctx, args)

@click.command(cls=DefaultHelp)
@click.option('-id', '--rec_id', help='rec_id')
#类似传入参数,如:@click.option('-id2', '--rec_id_2', help='rec_id_2')
def main(rec_id):
    """
        打印传入
    """
    print(rec_id)
if __name__ == '__main__':
    main()

使用如图:

Python click包详解,简单易用的命令行传入参数_第1张图片

你可能感兴趣的:(python,python)