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.