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

How to receive a string of sentences using click.option() in Python?


I am trying to create a simple command line interface to maintain to-do tasks.
I know that I can use click.argument() to get a string sentence from user but I want to have similar functionality using click.option().

@click.command()
@click.option('-a', '--add', type=click.STRING, help='Task you want to add')
@click.option('-rm', '--remove', type=click.INT, help='ID of task you want to remove')
def cli(add, remove):
    if add:
        add_task(add)
    elif remove:
        remove_task(remove)
    else:
        list()

As per the above script:
todo -a Hello World !!
Only gets the string "Hello", however I want the complete sentence.


Solution

  • according to the docs, all you need to do is add nargs=<the number you want> for example:

    @click.option('-a', '--add',nargs=2, type=click.STRING, help='Task you want to add')

    or you can always run you script like that:

    todo --add="Hello World !!"