7

If I do args.svc_name, I was expecting equivalent to args.option1, because the svc_name's value is option1. But i got error for "'Namespace' object has no attribute 'svc_name's'"

parser = argparse.ArgumentParser(prog=None,description="test")   
parser.add_argument("--option1", nargs="?",help="option")
args = parser.parse_args()
svc_name = "option1"
print (args.svc_name)

Can someone help me out?

Lucifer
  • 2,231
  • 3
  • 11
  • 8

1 Answers1

16

The ArgumentParser class exposes the keys as direct attributes rather than a mapping, so to get the attribute directly one would simply access it directly. As per the example from the question, it would simply be

print(args.option1)

If one wish to have some other variable (e.g. svc_name from the question) to store the attribute/flag to acquire the value from the argparser, simply turn it into a mapping (i.e. dict) using vars and then call the get method

print(vars(args).get(svc_name))

Or alternatively, getattr(args, svc_name).

metatoaster
  • 17,419
  • 5
  • 55
  • 66
  • Thanks. Just note (for my case) that `--num-max` will translate into `args.num_max` (i.e. dashes are converted to underscores). – Sridhar Sarnobat Jan 18 '22 at 08:11
  • 1
    @SridharSarnobat Yup, as [documented](https://docs.python.org/3/library/argparse.html#dest) - "Any internal `-` characters will be converted to `_` characters to make sure the string is a valid attribute name"; moreover, if `dest` is supplied, that will be the corresponding attribute name. – metatoaster Jan 19 '22 at 22:20