Pythons argparse for dummies

Python is a great language, but sometimes it makes life more complicated than necessary. I don’t know if this is because it’s heritage (C) or whether its creator is Italian 😉

Compared to Ruby which is created to “stay away” and make the programmers life as easy as possible, Python sometimes makes you read more documentation that you have ever expected.

The argparse library is a good example. If three weeks passes, I need to Google for examples on how to setup the darned thing. Instead of explaining the simple options that 99% of all users are interested in, it lists one complicated variant after another.

Therefore I have decided (for my own sake) to make a short and sweet Ruby-esqe documentation of this library

STRINGS or INTEGERS or FLOATS

Do this 99% of the time:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument( '-p')
args = parser.parse_args()
print(args.p)

If you dont give this argument, args.p will be None

peter@monster> python parm.py
None

If you give the argument -p, but no value, it will barf

peter@monster> python parm.py -p
usage: parm.py [-h] [-p P]
parm.py: error: argument -p: expected one argument

if you want a long option

parser.add_argument( '-p', '--product')

if you want it REQUIRED

parser.add_argument( '-p', '--product', required=True)

if you want a DEFAULT value

parser.add_argument( '-p', '--product', required=True, default="AAPL")

If you want the argument to be something other than STRING

parser.add_argument( '-n', '--number', type=integer)

FLAGS

Sometimes you want to pass a flag without a value. Skip your initial ideas about params of type bool with default values etc etc. DO THIS INSTEAD:

parser.add_argument('-w', action='store_true')

and args.w will be True or False

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.