Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to get value from argparse from variable, but not the name of the variable?

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?

like image 221
Lucifer Avatar asked Apr 26 '17 03:04

Lucifer


People also ask

How do you make an argument optional in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.

What does Argparse ArgumentParser ()?

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object: args = parser. parse_args() print(args.

What does parse_args return?

parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.

What is action Store_true in Argparse?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


1 Answers

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).

like image 167
metatoaster Avatar answered Nov 12 '22 12:11

metatoaster