pythonpython-click

Call the method according to the specified option Key by Python click


I checked the python click document and there seems to be no multiple option switch operation.I want click select the specified function to execute according to the options.

demo.py

import click

@click.command()
@click.option('-f', '--file', 'key', help='make file')
@click.option('-k', '--kill', 'key', help='kill proc')
@click.option('-p', '--proj', 'key', help="get proc")
def main(key):
    click.echo(key)

def make_file():
    print("make file")

def kill_proc():
    print("kill proc")

def get_proc():
    print("get proc")


if __name__ == '__main__':
    main()

expected result:

python demo.py -k 8080

kill proc


Solution

  • Probably you would have to use if/else to run expected command.

    But you could rather use @click.group() to create subcommand

    import click
    
    
    @click.group(chain=True)
    def main():
        pass
    
    
    @main.command('m')
    #@click.option('-k', '--key', help="proc ID")
    @click.argument('key')
    def make_file(key):
        print("make file", key)
    
    
    @main.command('k')
    #@click.option('-k', '--key', help="proc ID")
    @click.argument('key')
    def kill_proc(key):
        print("kill proc", key)
    
    
    @main.command('p')
    #@click.option('-k', '--key', help="proc ID")
    @click.argument('key')
    def get_proc(key):
        print("get proc", key)
    
    
    if __name__ == '__main__':
        main()
    

    And then you can run command without - (and commands may have own options

    script.py k 8000
    
    script.py p 8000
    

    Because I used chain=True in group so I can run together

    script.py k 8000 p 8000
    

    Doc: Commands and Groups and Advanced Patterns


    EDIT:

    Without group probably you would have to use if/else and unique names for options

    import click
    
    @click.command()
    @click.option('-f', '--file', 'f_key', help='make file')
    @click.option('-k', '--kill', 'k_key', help='kill proc')
    @click.option('-p', '--proj', 'p_key', help="get proc")
    def main(f_key, k_key, p_key):
        #print(f_key, k_key, p_key)
        
        if f_key:
            make_file(f_key)
        if k_key:
            kill_proc(k_key)
        if p_key:
            get_proc(p_key)
    
    def make_file(key):
        print("make file", key)
    
    def kill_proc(key):
        print("kill proc", key)
    
    def get_proc(key):
        print("get proc", key)
    
    if __name__ == '__main__':
        main()
    

    You can also run many options at once but commands can't have own options.

    script.py -p 8000 -k 1234