Search code examples
pythoncommand-line-interfacepython-click

Python click call command first then options


is there a way in Python Click library change the execution order?

I want to have cli my_command --options --options

now I have cli --options --options my_command

I don't want a command to be called at the end.


Solution

  • The structure of a click command is as follows:

    command <options> subcommand <subcommand options>
    

    I'm not sure how you would have two options with the same name for one command. However, the two '--options' options apply to the 'cli' command and not your 'my_command' command.

    To achieve something like what you want:

    import click
    
    @click.group()
    @click.option('--options/--not-options', default=False)
    def cli(options):
        if options:
            click.echo("Recieved options")
    
    @cli.command()
    @click.option('--options/--not-options', default=False)
    def my_command(options):
        if options:
            click.echo("Recieved options")
    
    if __name__ == '__main__':
        cli(obj={})
    

    To run this from the terminal (filename replaces the 'cli' command entrypoint):

    python mytool.py --options my-command --options
    
    >>Recieved options
    >>Received options