Forcing getopt to process a specific option first??

Dan Rawson daniel.rawson.take!this!out! at asml.nl
Thu Sep 18 14:17:39 EDT 2003


Skip Montanaro wrote:
>     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
> args:
> 
>     -f bar -o baz -c configfile -o bump -h
> 
> locate the '-c' and use it to split the argument list, then swap the two
> pieces:
> 
>     >>> 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
>     4
>     >>> 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']
> 
> Skip
> 
Thanks!  Either this solution or the one Peter Otten proposed will work . . .

Wow, two good solutions in an hour . . . .

Dan





More information about the Python-list mailing list