Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Weird error when assigning arg values to variables

I have a weird error thrown by python when trying to assign values from argparse to variables.

My code is:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--hostname', required=True)
    parser.add_argument('--username', default='root', type=str)
    parser.add_argument('--password', default='uy4h183D')
    parser.parse_args()
    hostname = args.hostname
    username = args.username
    password = args.password
    file = hostname + '.csv'
    print("The filename is {0}".format(file))
    main()

The error is:

./4collect.py --hostname bar 
Traceback (most recent call last):
File "./4collect.py", line 68, in <module>
hostname = args.hostname
NameError: name 'args' is not defined
like image 956
Leo Shatokhin Avatar asked Oct 13 '25 08:10

Leo Shatokhin


1 Answers

You need to assign args:

args = parser.parse_args()
like image 190
Hai Vu Avatar answered Oct 14 '25 22:10

Hai Vu



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!