When writing applications that take command-line arguments in Python, one has to make a choice between the two command-line parsing modules, getopt and optparse. Optparse though more powerful than getopt is available only since Python 2.3. Hence if you are writing a program targeted at Python 2.2 +, you are mostly constrained with using getopt and writing command line parsing code on top of it.
This recipe provides a solution to this problem. It masks the actual module used for option parsing from the application. If optparse is available it is used, otherwise the parser class defaults to getopt. The application only requires to pass a dictionary of option keys and their settings, in a format inspired by optparse, but using tuples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228  | # -- coding: iso8859-1
"""Generic option parser class. This class can be used
to write code that will parse command line options for
an application by invoking one of the standard Python
library command argument parser modules optparse or
getopt.
The class first tries to use optparse. It it is not there
(< Python 2.3), it invokes getopt. However, this is
transparent to the application which uses the class.
The class requires a dictionary with entries of the following
form for each command line option.
'option_var' :   ('short=<short option>','long=<long option>',
                  'help=<help string>', 'meta=<meta variable>',
                  'default=<default value>', 'type=<option type>')
where, 'option_var' is the key for the option in the final
dictionary of option-value pairs. The value is a tuple of
strings, where each string consists of entries of the form,
'key=value', where 'key' is borrowed from the way optparse
represents each variables for an option setting.
To parse the arguments, call the method 'parse_arguments'.
The return value is a dictionary of the option-value pairs."""
import sys
__author__="Anand Pillai"
class GenericOptionParserError(Exception):
    
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return str(self.value)
    
class GenericOptionParser:
    """ Generic option parser using
    either optparse or getopt """
    def __init__(self, optmap):
        self._optmap = self._parse_optmap(optmap)
        self._optdict = {}
        self.maxw = 24
        
    def _parse_optmap(self, map):
        """ Internal method -> Parse option
        map containing tuples and convert the
        tuples to a dictionary """
        optmap = {}
        for key,value in map.items():
            d = {}
            for item in value:
                if not item: continue
                var,val=item.split('=')
                d[var]=val
                
            optmap[key] = d
        return optmap
        
    def parse_arguments(self):
        """ Parse command line arguments and
        return a dictionary of option-value pairs """
        try:
            self.optparse = __import__('optparse')
            # For invoking help, when no arguments
            # are passed.
            if len(sys.argv)==1:
                sys.argv.append('-h')
            self._parse_arguments1()
        except ImportError:
            try:
                import getopt
                self.getopt = __import__('getopt')                
                self._parse_arguments2()
            except ImportError:
                raise GenericOptionParserError,'Fatal Error: No optparse or getopt modules found'
        return self._optdict
                
    def _parse_arguments1(self):
        """ Parse command-line arguments using optparse """
        p = self.optparse.OptionParser()
        
        for key,value in self._optmap.items():
            # Option destination is the key itself
            option = key
            # Default action is 'store'
            action = 'store'
            # Short option string
            sopt = value.get('short','')
            # Long option string
            lopt = value.get('long','')
            # Help string
            helpstr = value.get('help','')
            # Meta var
            meta = value.get('meta','')
            # Default value
            defl = value.get('default','')
            # Default type is 'string'
            typ = value.get('type','string')
            
            # If bool type...
            if typ == 'bool':
                action = 'store_true'
                defl = bool(str(defl) == 'True')
            if sopt: sopt = '-' + sopt
            if lopt: lopt = '--' + lopt
            
            # Add option
            p.add_option(sopt,lopt,dest=option,help=helpstr,metavar=meta,action=action,
                         default=defl)
        (options,args) = p.parse_args()
        self._optdict = options.__dict__
    def _parse_arguments2(self):
        """ Parse command-line arguments using getopt """
        # getopt requires help string to
        # be generated.
        if len(sys.argv)==1:
            sys.exit(self._usage())
        
        shortopt,longopt='h',['help']
        # Create short option string and long option
        # list for getopt
        for key, value in self._optmap.items():
            sopt = value.get('short','')
            lopt = value.get('long','')
            typ = value.get('type','string')            
            defl = value.get('default','')
            # If bool type...
            if typ == 'bool':
                defl = bool(str(defl) == 'True')
            # Set default value
            self._optdict[key] = defl
            if typ=='bool':
                if sopt: shortopt += sopt
                if lopt: longopt.append(lopt)
            else:
                if sopt: shortopt = "".join((shortopt,sopt,':'))
                if lopt: longopt.append(lopt+'=')
        # Parse
        (optlist,args) = self.getopt.getopt(sys.argv[1:],shortopt,longopt)
        # Match options
        for opt,val in optlist:
            # Invoke help
            if opt in ('-h','--help'):
                sys.exit(self._usage())
                
            for key,value in self._optmap.items():
                sopt = '-' + value.get('short','')
                lopt = '--' + value.get('long','')
                typ = value.get('type','string')
                
                if opt in (sopt,lopt):
                    if typ=='bool': val = True
                    self._optdict[key]=val
                    del self._optmap[key]
                    break
    def _usage(self):
        """ Generate and return a help string
        for the program, similar to the one
        generated by optparse """
        usage = ["usage: %s [options]\n\n" % sys.argv[0]]
        usage.append("options:\n")
        options = [('  -h, --help', 'show this help message and exit\n')]
        maxlen = 0
        for value in self._optmap.values():
            sopt = value.get('short','')
            lopt = value.get('long','')
            help = value.get('help','')
            meta = value.get('meta','')
            
            optstr = ""
            if sopt: optstr="".join(('  -',sopt,meta))
            if lopt: optstr="".join((optstr,', --',lopt))
            if meta: optstr="".join((optstr,'=',meta))
            
            l = len(optstr)
            if l>maxlen: maxlen=l
            options.append((optstr,help))
            
        for x in range(len(options)):
            optstr = options[x][0]
            helpstr = options[x][1]
            if maxlen<self.maxw - 1:
                usage.append("".join((optstr,(maxlen-len(optstr) + 2)*' ', helpstr,'\n')))
            elif len(optstr)<self.maxw - 1:
                usage.append("".join((optstr,(self.maxw-len(optstr))*' ', helpstr,'\n')))
            else:
                usage.append("".join((optstr,'\n',self.maxw*' ', helpstr,'\n')))                
        return "".join(usage)
if __name__=="__main__":
    d={ 'infile' : ('short=i','long=in','help=Input file for the program',
                    'meta=IN'),
        'outfile': ('short=o','long=out','help=Output file for the program',
                    'meta=OUT'),
        'verbose': ('short=V','long=verbose','help=Be verbose in output',
                    'type=bool') }
    g=GenericOptionParser(d)
    optdict = g.parse_arguments()
 
    for key,value in optdict.items():
         # Use the option and the value in
         # your program
         ...
 | 
Using the option parser in this recipe, it is straightforward to incorporate generic command line parsing in your application.
Sample usage below:
Dictionary with option settings
d={ 'infile' : ('short=i','long=in','help=Input file for the program', 'meta=IN'), 'outfile': ('short=o','long=out','help=Output file for the program', 'meta=OUT'), 'verbose': ('short=V','long=verbose','help=Be verbose in output', 'type=bool') }
g=GenericOptionParser(d) optdict = g.parse_arguments()
for key,value in optdict.items(): # Use the option and the value in # your program ...
I have seen Python programmers having to write custom code when faced with the task of doing command line argument parsing. Some use optparse which limits your application to Python 2.3 +, some stick to getopt which makes sure that the program works with all versions of Python, but loses the power of optparse. Some uses neither and develops custom code.
This class resolves the dilemma, by providing a single mechanism which wraps up both optparse and getopt. One advantage of this is that you get the power of optparse, if you are working with versions of Python before 2.3 .
Download
Copy to clipboard
Optik. You can save a lot of trouble by simply installing Optik for older versions of Python. Optik was renamed optparse when it was included in Python. Then simply do:
Agree, but. I agree, but optik is not available in the standard library. If you are constrained to use only the standard library, then this recipe is helpful.
-Anand
That makes no sense. If you can use this recipe, you can just as easily use optik. Neither are in the standard library.
I does make sense. ... because if you used Optik you would have to distribute it with your software for it to be able to run right out-of-the-box. This might not always be feasible, for example if you're just writing a one-file script or if the BSD licence of Optik is not compatible with the one your software uses.
BSD license not compatible with the license your software uses? Not possible unless the license your software uses is braindead.