Simple argparse example wanted: 1 argument, 3 results Simple argparse example wanted: 1 argument, 3 results python python

Simple argparse example wanted: 1 argument, 3 results


Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program')parser.add_argument('-f','--foo', help='Description for foo argument', required=True)parser.add_argument('-b','--bar', help='Description for bar argument', required=True)args = vars(parser.parse_args())

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':    # code hereif args['bar'] == 'World':    # code here

In your case simply add only one argument.


My understanding of the original question is two-fold. First, in terms of the simplest possible argparse example, I'm surprised that I haven't seen it here. Of course, to be dead-simple, it's also all overhead with little power, but it might get you started.

import argparseparser = argparse.ArgumentParser()parser.add_argument("a")args = parser.parse_args()if args.a == 'magic.name':    print 'You nailed it!'

But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the original question. Matt Wilkie seems to want a single optional argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:

...parser.add_argument("a", nargs='?', default="check_string_for_empty")...if args.a == 'check_string_for_empty':    print 'I can tell that no argument was given and I can deal with that here.'elif args.a == 'magic.name':    print 'You nailed it!'else:    print args.a

There may well be a more elegant solution, but this works and is minimalist.


The argparse documentation is reasonably good but leaves out a few useful details which might not be obvious. (@Diego Navarro already mentioned some of this but I'll try to expand on his answer slightly.) Basic usage is as follows:

parser = argparse.ArgumentParser()parser.add_argument('-f', '--my-foo', default='foobar')parser.add_argument('-b', '--bar-value', default=3.14)args = parser.parse_args()

The object you get back from parse_args() is a 'Namespace' object: An object whose member variables are named after your command-line arguments. The Namespace object is how you access your arguments and the values associated with them:

args = parser.parse_args()print (args.my_foo)print (args.bar_value)

(Note that argparse replaces '-' in your argument names with underscores when naming the variables.)

In many situations you may wish to use arguments simply as flags which take no value. You can add those in argparse like this:

parser.add_argument('--foo', action='store_true')parser.add_argument('--no-foo', action='store_false')

The above will create variables named 'foo' with value True, and 'no_foo' with value False, respectively:

if (args.foo):    print ("foo is true")if (args.no_foo is False):    print ("nofoo is false")

Note also that you can use the "required" option when adding an argument:

parser.add_argument('-o', '--output', required=True)

That way if you omit this argument at the command line argparse will tell you it's missing and stop execution of your script.

Finally, note that it's possible to create a dict structure of your arguments using the vars function, if that makes life easier for you.

args = parser.parse_args()argsdict = vars(args)print (argsdict['my_foo'])print (argsdict['bar_value'])

As you can see, vars returns a dict with your argument names as keys and their values as, er, values.

There are lots of other options and things you can do, but this should cover the most essential, common usage scenarios.