python单击,使选项值可选 [英] python click, make option value optional

查看:81
本文介绍了python单击,使选项值可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 2 单击.我的工具要么需要写一个值,要么读取它,或者不更改它.如果可以执行以下操作,那就太好了:

I am working on a small command line tool using Python 2 and click. My tool either needs to write a value, read it, or do not change it. It would be nice if I could do the following:

mytool --r0=0xffff ..........将值r0设置为0xffff
mytool --r0 ......................读取值r0
mytool ...............................对r0

mytool --r0=0xffff..........Set value r0 to 0xffff
mytool --r0......................Read value r0
mytool...............................Don't do anything with r0

根据文档,似乎不可能,但是我可能会错过它.那么有可能还是我必须找到另一种方法?

Based on the documentation, it doesn't seem possible, but I could have missed it. So is it possible or do I have to find a different approach?

推荐答案

解决此问题的一种方法是引入另一个名为r0_set的参数.然后,为了保留所需的命令行,我们可以从click.Command继承而来parse_args,将用户输入的r0=0xffff转换为r0_set=0xffff

One way to solve this problem is to introduce another parameter named r0_set. And then to preserve the desired command line, we can inherit from click.Command and over ride parse_args to turn the user entered r0=0xffff into r0_set=0xffff

代码:

class RegisterReaderOption(click.Option):
    """ Mark this option as getting a _set option """
    register_reader = True

class RegisterWriterOption(click.Option):
    """ Fix the help for the _set suffix """
    def get_help_record(self, ctx):
        help = super(RegisterWriterOption, self).get_help_record(ctx)
        return (help[0].replace('_set ', '='),) + help[1:]

class RegisterWriterCommand(click.Command):
    def parse_args(self, ctx, args):
        """ Translate any opt= to opt_set= as needed """
        options = [o for o in ctx.command.params
                   if getattr(o, 'register_reader', None)]
        prefixes = {p for p in sum([o.opts for o in options], [])
                    if p.startswith('--')}
        for i, a in enumerate(args):
            a = a.split('=')
            if a[0] in prefixes and len(a) > 1:
                a[0] += '_set'
                args[i] = '='.join(a)

        return super(RegisterWriterCommand, self).parse_args(ctx, args)

测试代码:

@click.command(cls=RegisterWriterCommand)
@click.option('--r0', cls=RegisterReaderOption, is_flag=True,
              help='Read the r0 value')
@click.option('--r0_set', cls=RegisterWriterOption,
              help='Set the r0 value')
def cli(r0, r0_set):
    click.echo('r0: {}  r0_set: {}'.format(r0, r0_set))

cli(['--r0=0xfff', '--r0'])
cli(['--help'])

结果:

r0: True  r0_set: 0xfff


Usage: test.py [OPTIONS]

Options:
  --r0       Read the r0 value
  --r0=TEXT  Set the r0 value
  --help     Show this message and exit.

这篇关于python单击,使选项值可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆