Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a python argparse argument with a dot in the name

Python's argparse lets me define argument names containing a dot in the name. But how can I access these ?

import argparse


parser = argparse.ArgumentParser()
parser.add_argument("inputfile.txt")
parser.add_argument("outputfile.txt")

args = parser.parse_args(['hello', 'world'])

# now args is:
# Namespace(inputfile.txt='hello', outputfile.txt='world')


# and this does not work
print(args.inputfile.txt)
>>> AttributeError: 'Namespace' object has no attribute 'inputfile'

Obviously attribute names can be created with a dot in their name but how can these be accessed ?

Edit: My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile".

After trying some of the suggestions the easiest way to accomplish this is using the metavar option:

parser.add_argument("inputfile", metavar="inputfile.txt")
like image 623
gollum Avatar asked Jan 07 '23 16:01

gollum


1 Answers

Internally, argparse will add all attributes to the Namespace() instance with setattr. Accordingly, you can access the values with getattr:

getattr(args, 'inputfile.txt')

However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the dest option of argparse.add_argument to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.

like image 154
lemonhead Avatar answered Jan 26 '23 11:01

lemonhead