Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store argparse values in variables?

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

like image 990
biohax2015 Avatar asked Mar 21 '14 22:03

biohax2015


People also ask

What does Argparse ArgumentParser () do?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .

What does Nargs do in Argparse?

The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.

What is Store_true in Python?

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.


1 Answers

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
like image 72
khagler Avatar answered Oct 08 '22 19:10

khagler