Search code examples
pythonpython-click

Error: No such option yet I've clearly set the option up


I'm just starting out with a simple project and using the Click library and have hit a snag early on that I can't figure out. When I run this with the "--testmode" flag it shows as True however the subsequent function doesn't execute and I get an error that no such option is defined? What am I doing wrong here?

import click

@click.command()
@click.option('--user', prompt=True)
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False)
def authenticate(user, password):
    pass

@click.command()
@click.option('--age')
@click.option('--testmode', is_flag=True)
def main(age, testmode):
    print('Age: ', age)
    print('Testmode: ', testmode)

    if testmode:
        authenticate()

if __name__ == "__main__":
    main()

Console output:

python .\dev.py --help
Usage: dev.py [OPTIONS]

Options:
  --age TEXT
  --testmode
  --help      Show this message and exit.


python .\dev.py --testmode
Age:  None
Testmode:  True
Usage: dev.py [OPTIONS]
Try 'dev.py --help' for help.

Error: no such option: --testmode

Solution

  • The problem is here:

        if testmode:
            authenticate()
    

    You're calling authenticate() like a function, but you've defined it as another click.command. That means it's going to look at sys.argv for command line options, find --testmode, and compare that against the options you defined with @click.option.

    The authenticate method doesn't have a --testmode option, hence the error you're seeing.

    There are various ways to fix this. Does authenticate really need to be configured as a command? The way you've got your code set up right now there's no way to call it via the command line.