Forcing getopt to process a specific option first??

Jeff Epler jepler at unpythonic.net
Thu Sep 18 20:32:14 EDT 2003


Care for another solution?

I'd simply do two passes over the argument list.  This has an advantage
over both the other alternatives proposed.  First, it works if the user
writes something like "-bccf" (equivalent to the arguments ["-b", "-c", "cf"]),
and second it works with repeated options like [-a", "x", "-a", "y"].

This doesn't work if something in the configuration file could affect
the available set of commandline switches.  There may be some other
shortcoming I haven't considered yet, too.

Jeff

########################################################################
# Program
import getopt

def main(argv):
        args, rest = getopt.getopt(argv, "c:a:b")

        # First pass, parse any -c option
        for k, v in args:
                if k == "-c":
                        print "Using config file", v

        # Next, parse the other options
        for k, v in args:
                if k == "-c": continue
		print "Processing switch", k, v


	print "Remaining positional arguments", rest
argv = "-a x -bccf -a y ...".split()
main(argv)

########################################################################
# Output
Using config file cf
Processing switch -a x
Processing switch -b 
Processing switch -a y
Remaining positional arguments ['...']





More information about the Python-list mailing list