Just for general interest, here's my little argument parser:
import sys
def getopt (param, default=None):
"""Return a named parameter value from the command line.
The parameter and its value must be of the form
-param value
The parameter string and its following value are removed
from sys.argv. If the parameter is not present on the command line,
then the value of the variable is not changed, and nothing
is removed from sys.argv.
Param can be a flag (that is, a boolean will be returned and the
value on the command line following the flag will not be returned
or consumed) if the "default" parameter is omitted or None.
Typical code for this usage would be:
WANT_HELP = getopt('-h')
if WANT_HELP:
print(__doc__)
sys.exit(1)
NOTE: this function converts the result type to the type
of "default" - e.g., int(), float(), or bool().
ARGUMENTS
param -- the name of the command line option, including the
'-' character if used.
default -- the default value for the parameter. If omitted,
the function returns True if the param is present.
RETURNS
the new value of the parameter, or the default value if param
is missing from the command line, or True if param is a flag
(i.e., "default" is omitted or None).
"""
try:
opt = sys.argv.index(param)
del sys.argv[opt]
if default is not None:
option = type(default)(sys.argv.pop(opt))
else:
option = True # don't consume the next parameter
except ValueError:
option = default # param is not in sys.argv
except IndexError:
msg = '"%s" parameter is missing its required value' % param
raise ValueError(msg)
return option