Command line handling in Python with optparse
Apr 2nd, 2009 by harijay
Command lines interfaces to programs are very empowering. I started using computers with the Linux command line and I have never strayed too far from programs that are predominantly command line based. Whether it was rasmol , povray , phenix or ffmpeg I always found that the command line gave the program a more transparent interface . By that I mean it was easier ( at least for me ) to figure out how to do decipher a manual page than to go looking for a particular functionality in a GUI window.
No in the case of python , I have been writing scripts that take in user input from the command line for a while now. In these scripts , I would generally accept only one input and that would be the first in the sys.argv list. If I had more than one input I would iterate over the input list and try and figure out what the inputs were . Even worse in most cases I would hard code the order of inputs into my code ( terrible practise). Fortunately for me , my discovery of the optparse module has changed all that.
The optparse module is an object oriented ( dont let that scare you) and super-intuitive way to add command line options to any python scriptSo say you want to add an input file command line switch with the -i attribute , All you have to do is
from optparse import OptionParser
optparse_object =OptionParser()
optparser_object.add_option(”-i”,”–infile”, dest=”infile”,help=”input file for script” , metavar=”[infile.txt]“)
Once you do this you can easily have the module parse the sys.argv list and make sense of it .So you would add the following line
options_object, spillover_options = optparser_object.parse_args()
Then options_object.infile will have the value of the input option . This is specified by the dest section in the add_option argument list) . The nice thing with the module is that all possibilities can be mapped to the same options_object.infile destination . So for eg I have mapped “-i” and “–infile” to the same destination .Even better is the option to add a help string with the help=”help text” argument . This help is then printed out if the user provides an option that the script cannot handle or if the code specifically calls the optparser_object.print_help() function.
For a concrete example on how to use the opt_parse module consult the docs or my example code on github .
[...] post is about trying to get back into the groove by telling you about argparse . Having talked about optparse and command line parsing , I heard about argparse thanks to a talk that I caught by clicking a [...]
This was very helpful. Thanks.