18

I am trying to add command line options to my script, using the following code:

import argparse parser = argparse.ArgumentParser('My program') parser.add_argument('-x', '--one') parser.add_argument('-y', '--two') parser.add_argument('-z', '--three') args = vars(parser.parse_args()) foo = args['one'] bar = args['two'] cheese = args['three'] 

Is this the correct way to do this?

Also, how do I run it from the IDLE shell? I use the command 'python myprogram.py -x foo -y bar -z cheese' and it gives me a syntax error

3 Answers 3

34

That will work, but you can simplify it a bit like this:

args = parser.parse_args() foo = args.one bar = args.two cheese = args.three 
Sign up to request clarification or add additional context in comments.

Comments

7

use args.__dict__

args.__dict__["one"] args.__dict__["two"] args.__dict__["three"] 

4 Comments

I agree your solution is correct. And interesting,. At the same time, some people on SO get really cranky and downvote if a Python domain answer is not in what they see as acceptable pythonic form. Meh. Even though what is "acceptable" changes over time.
@DavidPointer is what it is I guess. Thanks for the pity votes :P
I don't know. After all the OP already used vars() which already returns the _dict_
It's "working" but it's to be avoided. The presence of the underscores is a strong hint that these methods are not intended to be invoked directly. Therefore, yes, it's working, but no, it's not a good answer. So I understand that some people downvote it.
3

The canonical way to get the values of the arguments that is suggested in the documentation is to use vars as you did and access the argument values by name:

argv = vars(args) one = argv['one'] two = args['two'] three = argv['three'] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.