Leo Shatokhin Leo Shatokhin - 11 months ago 40
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

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')
hostname = args.hostname
username = args.username
password = args.password
file = hostname + '.csv'
print("The filename is {0}".format(file))

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 Source

You need to assign args:

args = parser.parse_args()