pythonargparsedefaults

Can argparse be used to initialize default values for strings


I'd like to initialize essential variables for my Python script (3.4), while providing the end user a chance to change those variable definitions via command line options. Looks like argparse is the way to go. I've looked here to get started, and this has worked for all my use cases except the one below:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--con',dest='targFileName',default='targets.con')
args = parser.parse_args()
print(targFileName)

Resulting in an error:

bash-4.1$ python test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
print(targFileName)
NameError: name 'targFileName' is not defined.

Surely I'm misreading the doc. What's missing?


Solution

  • You use args = parser.parse_args(), but that does not define all of the arguments in the global scope. That just returns an instance of a class that has attributes for your arguments. To get that argument, use args.targFileName. You could also say args = vars(parser.parse_args()) so that you could use args['targFileName'].