Parsing command line options

Chris Liechti cliechti at gmx.net
Thu May 23 17:51:36 EDT 2002


Daniel Klein <danielk at aracnet.com> wrote in
news:3nmqeu837rvb7laatj4pfaeblgu853siu1 at 4ax.com: 

> I am converting a Java application to Python. The application has
> several optional '-Dproperty=value' commandline options that can be
> specified in any combination and in any sequence. Is there something
> equivalent in Python? 
> 
> I took a look at the 'getopt' module but the Python commandline does
> not allow you to use options other than those that are
> 'understandable' by the interperator. The only way I can figure to
> implement this is to create my own syntax and pass these as arguments
> to sys.argv. 
> 
> Am I on the right track or am I derailed? ;-)
> 
> Daniel Klein
> 
that should work very well with getopt.
something like that (untested):

    try:
        opts, args = getopt.getopt(sys.argv[1:],
            "D:",
            ["define=",]
        )
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ("-D", "--define"):
    	    	    	try:
    	    	    	    	key, value = a.split('=')
    	    	    	    	#...
    	    	    	except ValueError:
    	    	    	    	#error in arg, no or more than one =


use it like:
$ python script.py -Dhello=123

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list