2

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Yahya
  • 318
  • 3
  • 11
  • Duplicate question:https://stackoverflow.com/questions/44247099/click-command-line-interfaces-make-options-required-if-other-optional-option-is – tomgalpin Jan 14 '20 at 13:50
  • If you have a new question then you must create a new post as indicated by the SO rules. – eyllanesc Jan 14 '20 at 16:45

1 Answers1

2

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.

rassar
  • 5,412
  • 3
  • 25
  • 41
  • thankyou very much for your answer. One thing I could not understand is `user, new_user = user`. This means that `user, new_user` should have the same value, but they should not because they have different values (in case of yes, user=True and new_user = no). Can you please say a few words about this? – Yahya Jan 14 '20 at 14:02
  • @Yahya Added an explanation - it's due to tuple unpacking. – rassar Jan 14 '20 at 14:55
  • 1
    `user, new_user = user` here `user` on the right side is basically calling the `prompt_user` that returns two values. am I right? – Yahya Jan 14 '20 at 15:12
  • thanks, one more question please. is it possible to print a custom message between two `click.option()`? – Yahya Jan 14 '20 at 15:18
  • You can always change `click.prompt('username')` to display whatever you want, or add more `print` statements before it. – rassar Jan 14 '20 at 15:35
  • sorry I didn't mean that. can you please see the updated question? – Yahya Jan 14 '20 at 16:43
  • @Yahya If you have a new question then you must create a new post as indicated by the SO rules. – eyllanesc Jan 14 '20 at 16:45
  • This is the link for the other question: https://stackoverflow.com/q/59738600/11243953 – Yahya Jan 14 '20 at 17:07