Search code examples
pythonpython-3.xcommand-line-interfacepython-click

How to show/hide input option based on the first input?


I'm writing a command-line tool using Python Click package.

For the user input, I want to show/hide the next input option based on the first input.

Here is the sample code:

import click


@click.command()
@click.option('--user/--no-user', prompt='do you want to add user?')
@click.option('--new-user', prompt='add user')
def add_user(user, new_user):
    print(user)
    print(new_user)


add_user()

I want to show 2nd prompt('--new-user') only if the user type yes for the first input('--user/--no-user').

Any help how can I do this? Thanks in advance.


Solution

  • You would have to use a custom callback:

    import click
    
    def prompt_user(ctx, param, user):
        new_user = None
        if user:
            new_user = click.prompt('username')
        return (user, new_user)
    
    
    @click.command()
    @click.option('--user/--no-user', prompt='do you want to add user?', callback=prompt_user)
    def add_user(user):
        user, new_user = user
        print(user)
        print(new_user)
    
    if __name__ == '__main__':
        add_user()
    
    $ python3.8 user.py
    do you want to add user? [y/N]: y
    username: no
    True
    no
    $ python3.8 user.py
    do you want to add user? [y/N]: N
    False
    None
    
    

    Note that prompt_user returns a tuple of two values. So the line user, new_user = user sets user equal to the first value and new_user to the second. See this link for more explanation.