Skip to content

Instantly share code, notes, and snippets.

@jathanism
Last active February 27, 2019 22:23
Show Gist options
  • Select an option

  • Save jathanism/35fc0dc7512bd898798624730c730e13 to your computer and use it in GitHub Desktop.

Select an option

Save jathanism/35fc0dc7512bd898798624730c730e13 to your computer and use it in GitHub Desktop.
Click/Gflags compatibiltiy.
"""
Click gflags compatibility, provides a click.Command subclass that plays
nicely with gflags, passing any unknown arguments to it and combining the
help text.
Use me like this:
@click.command(cls=GflagsCommand)
def foo(bar):
...
"""
import click
import gflags
class GflagsCommand(click.Command):
"""
Click Command class that provides compatibility with gflags. Any
arguments/options that click does not parse are passed on to gflags for its
parsing.
To use this in your project, use the click.command decorator like so:
@click.command(cls=GflagsCommand)
def my_command():
pass
"""
def parse_args(self, ctx, args):
# Help gflags skip over options it doesn't know about which lack a =,
# like: '--some_opt value'. This also allows mixing of flag and
# non-flag arguments, which is click's default.
gflags.FLAGS.UseGnuGetOpt()
# Parse gflags options first. If this is done the other way around,
# then click will try to consume gflags as Arguments instead of
# assuming they're Options.
gflags_args = [ctx.info_name] + args
extra_args = gflags.FLAGS(gflags_args, known_only=True)
# Trim program name from the extra args that gflags gives us
extra_args = extra_args[1:]
extra_args = super(GflagsCommand, self).parse_args(ctx, extra_args)
return extra_args
def get_help(self, ctx):
"""
Get the Click help text along with the gflags help
"""
help_text = super(GflagsCommand, self).get_help(ctx)
help_text += "\n\n\n"
help_text += "Additionally these options are available via gflags:\n"
help_text += gflags.FLAGS.GetHelp()
return help_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment