Click: NameError: name not defined

bclayman

I'm trying to use click to pass command-line arguments to a function but having difficulty. I'm trying to pass two command-line arguments with this:

python script.py --first-a hi --second-a there

Here's my attempt:

import click
@click.command()
@click.option("--first-a")
@click.option("--second-a")
def main(first_a, second_a):
    print first_a, second_a

if __name__ == "__main__":
    main(first_a, first_a)

This fails with:

NameError: name 'first_a' is not defined

I thought this had to do with dashes vs. underscores but removing the dashes and underscores (just using firsta and seconda) also fails with the same issue.

What am I doing incorrectly?

Stephen Rauch

You need to call main() either without any arguments, or with a list of parameters as would normally be found in sys.argv.

Code:

if __name__ == "__main__":
    main()

Test Code:

import click

@click.command()
@click.option("--first-a")
@click.option("--second-a")
def main(first_a, second_a):
    print(first_a, second_a)

if __name__ == "__main__":
    # test code
    import sys
    sys.argv[1:] = ['--first-a', 'hi', '--second-a', 'there']

    # actual call to click command
    main()

Results:

hi there

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related