Leo Shatokhin Leo Shatokhin - 3 months ago 8
Python Question

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

Answer

You need to assign args:

args = parser.parse_args()
Comments