Parsing your script's command line options from scratch is a pain. There is a function called getopt() which comes from C and is used in many languages such as Perl and Python to help you with this task. But it still requires quite a bit of manual work, and nowadays most scripting languages have gone beyond getopt to make command line options easy to process.
Optparse is a standard part of the Python library. Here is an example of its usage. We will create a function called process_args() that does most of the work.
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-a", "--add", action="store_true", dest="add",
help="Add a name to my database.")
parser.add_option("-n", "--name", action="store", dest="name",
help="Name to add to my database.")
The first add_option() has an action "store_true" with a dest of add. This means that the option is a boolean with no arguments and will store the value of True in a variable called "add". You could also use "store_false" to create a boolean argument that stores a value of False.
The second add_option() has an action of "store", so it does take an argument, which it will put into the variable called "name".
Now that you have created your parsing function, you can call it from your main routine.
(opts, args) = process_args()
if opts.add == True:
print "You used the --add option.\n"
if opts.name is not None:
print "You used the --name option with the argument of %s\n." % opts.name
I didn't need to tell it what to parse, because by default it parses ARGV. I also didn't use the second value returned by process_args. It is a list containg the arguments that you passed to your options.
A nice feature of Optparse is that it automatically creates a --help option based on the help strings you passed to add_option(). Here is what the help output looks like for our script.
$ ./myscript --help
usage: myscript [options]
-h, --help show this help message and exit
-a, --add Add a name to my database.
Name to add to my database.