Forcing getopt to process a specific option first??

Skip Montanaro skip at
Thu Sep 18 19:07:11 CEST 2003

    Dan> Is there any way to force getopt to process one option first??  I'd
    Dan> like to be able to pass in the name of a configuration file for my
    Dan> application, then have the remaining command-line parameters
    Dan> over-ride the configuration file if they are present.

Not that I'm aware of.  If the order of the remaining options doesn't
matter, you might try splitting the argument list before the option which
introduces your config file.  For example, given this set of command line

    -f bar -o baz -c configfile -o bump -h

locate the '-c' and use it to split the argument list, then swap the two

    >>> s = "-f bar -o baz -c configfile -o bump -h"
    >>> args = s.split()
    >>> args
    ['-f', 'bar', '-o', 'baz', '-c', 'configfile', '-o', 'bump', '-h']
    >>> index = args.index('-c')
    >>> index
    >>> args[:index], args[index:]
    (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile', '-o', 'bump', '-h'])
    >>> args = args[index:] + args[:index]
    >>> args
    ['-c', 'configfile', '-o', 'bump', '-h', '-f', 'bar', '-o', 'baz']

Now pass that list to getopt.getopt().

If the order of the remaining arguments does matter, you just split the
argument list into three pieces, the part before rearranging:

    >>> args[:index], args[index:index+2], args[index+2:]
    (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile'], ['-o', 'bump', '-h'])
    >>> args = args[index:index+2] + args[:index] + args[index+2:]
    >>> args
    ['-c', 'configfile', '-f', 'bar', '-o', 'baz', '-o', 'bump', '-h']


More information about the Python-list mailing list