Search code examples
pythonpython-3.xpython-2.7command-line-interfacepython-click

Creating a click command that accepts two different sets of arguments


Through the python package click I have legacy code that looks as followed on the command line:

toolName toolCommand arugment

I have updated the legacy code for the command to accept three arguments now:

toolName toolCommand arugment1 argument2 argument3

While the new code meets new standards, the legacy code is still valuable and could be used/needed. Would anyone know if it's possible through the click package manager to allow users to decide which arguments (legacy or new standards) to use for their needs?


Solution

  • I ended up using clicks flags to resolve this issue.

    If a flag for legacy code was present then it would run the code as if it was legacy. If the flag was for the modernized code was present it would run the code from the latest version.

    Edit: Even better you can split it into sub commands:

    @click.group(invoke_without_command=False)
    @click.pass_context
    def cli(ctx):
        pass
    
    @cli.command('subcommand_1', short_help='Function does x thing.')
    #Arguments/Paramaters
    .............
    ............
    ............
    def subcommand_1:
        #Code
    
        #End of funcction
    
    # write another subcommand
    # write arguments/options
    # define sub command
    

    When calling the command you'd do:

    toolName command_name subcommand_name arguments/options