Click: [HELP] option without command

Created on 5 Dec 2018  路  3Comments  路  Source: pallets/click

How can I create an option without having to supply a command? Similar to --help

Code:

@click.option("--debug/--no-debug", default=False)
@click.option(
    "--profile",
    help=(
        "What profile to be used when interacting with AWS. If you are "
        "on macOS or Linux you are recommended to use limes instead of "
        "specifying a profile explicitly."
    ),
)
@click.option("--version", is_flag=True)
@click.pass_context
def cli(ctx, debug, profile, version):
    if version:
        print_version()
        exit(0)
    ctx.obj["DEBUG"] = debug
    ctx.obj["AWS_PROFILE"] = profile


def print_version():
    import pkg_resources

    version = pkg_resources.require("dpo-python-helpers")[0].version
    print(version)


def main():
    cli(obj={})

If I run dev-env --version

I get:

Usage: dev-env [OPTIONS] COMMAND [ARGS]...
Try "dev-env --help" for help.

Error: Missing command.

I've tried using default=False instead of is_flag=True, but that didn't change anything.

Click===7.0
Python 3.7.0

Most helpful comment

For anyone come here to use options without commands, use invoke_without_command=True

example: pipenv/cli/command.py#L35

All 3 comments

Solved it my damn self! 馃槃

def print_version(ctx, param, value):
    import pkg_resources

    if not value or ctx.resilient_parsing:
        return

    version = pkg_resources.require("dpo-python-helpers")[0].version
    print(version)
    ctx.exit(0)

@click.option("--debug/--no-debug", default=False)
@click.option(
    "--profile",
    help=(
        "What profile to be used when interacting with AWS. If you are "
        "on macOS or Linux you are recommended to use limes instead of "
        "specifying a profile explicitly."
    ),
)
@click.option(
    '--version',
    help="Print the package version and exit.",
    is_flag=True,
    expose_value=False,
    is_eager=True,
    callback=print_version
)
@click.pass_context
def cli(ctx, debug, profile):
    ctx.obj["DEBUG"] = debug
    ctx.obj["AWS_PROFILE"] = profile

lol, even better

@click.version_option(None, "-v", "--version", message="%(version)s")

For anyone come here to use options without commands, use invoke_without_command=True

example: pipenv/cli/command.py#L35

Was this page helpful?
0 / 5 - 0 ratings