Forcing getopt to process a specific option first??

Peter Otten __peter__ at
Thu Sep 18 19:52:36 CEST 2003

Dan Rawson wrote:

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

The easiest solution would be to make the config file the mandatory first
argument of the command line and then call

getopt.getopt(sys.argv[2:], options)

Below is another approach, that might fit your needs:

import getopt

#sample args
args = ["-c", "config.txt", "-r", "-i", "specialin.txt"]

options, args = getopt.getopt(args, "c:ri:o:")
useroptions = dict(options)

if "-c" in useroptions:

    #set defaults
    defaultoptions = {"-i": "defaultin.txt", "-o": "defaultout.txt"}

    del useroptions["-c"]

    #override defaults
    options = defaultoptions.items()

print options


More information about the Python-list mailing list