You will probably agree with me that one of the most boring programming chores is the parsing of command line arguments. After programming one too many argument handling routine I decided to write a utility that does the job for me.
As you can see, the main action is on lines 15-28. I opted for a more declarative approach i.e. I wanted to be able to “declare” the expected command line arguments (along with their types and default values) and be done.
The first three values were supplied on the command line whereas the last two stem from defaults declared in the client code (see lines 20 and 23 above).
!! Invalid parameter value: invalid literal for int(): abc !!
!! Error: option -z not recognized !!
4  file for an example showing how it should be used.
21          """initialiser, just copies its arguments to attributes"""
lines 20-27 (initialiser method): merely copies the parameters passed to it to attributes of the same name.
lines 35-41: the data required for the getopt() function is put together (from the the command line argument “declaration” supplied by the client code). Subsequently getopt() is invoked to perform the low level argument parsing.
It is used to add the arguments that were actually supplied on the command line to the suppliedd dictionary. Please note again, how python type functions are used to convert (any non-boolean) command line arguments from strings to the desired type (line 65).
lines 71-73: last but not least we merge the arguments that were actually supplied on the command line to the default values and return the result.
In case of an error check_args() will invoke the help() function which terminates the program execution after printing a help string (if any was supplied).
In case you liked the command line argument processing class introduced above, please feel free to download it from here here and play with it. The colorised source code without any interspersed commentary can be viewed here.