Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click: NameError: name not defined

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?

like image 357
anon_swe Avatar asked Aug 02 '26 01:08

anon_swe


1 Answers

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
like image 69
Stephen Rauch Avatar answered Aug 04 '26 14:08

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!