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
Code:
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)
Test Code:
@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'])
Results:
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.
@click.option('--count', default=1, help='Number of greetings.')
– Concupiscencedefault
– Gaberlunziedefault
? – Concupiscenceset register to a value of 1
. In other words calling justmytool
would be equivalent tomytool --r0=1
, which meansset register 0 to 1
which is not my intent. – Gaberlunzie-2
to mean nothing,-1
to mean read and0
to0xffffffff
to mean a write. But I think it is a bit ugly. Say I want to readr0
.mytool --r0
looks much better rather thanmytool --r0=-1
. It just doesn't look clean. – Gaberlunzie