pythonwebspherejythonwebsphere-6.1wsadmin

Parsing command line options in Jython 2.1


I'm using Jython 2.1 for wsadmin scripting and want to find a better way of parsing command line options. I'm currently doing this:

-> deploy.py foo bar baz

and then in the script:

foo = sys.arg[0]
bar = sys.arg[1]
baz = sys.arg[2]

but would like to do this:

-> deploy.py -f foo -b bar -z baz

optparse was added to python in 2.3. What other options do I have in Jython 2.1?


Solution

  • How about something like this:

    args = sys.argv[:]  # Copy so don't destroy original
    while len(args) > 0:
        current_arg = args[0]
    
        if current_arg == '-f':
            foo = args[1]
            args = args[2:]
        elif current_arg == '-b':
            bar = args[1]
            args = args[2:]
        elif current_arg == '-z':
            baz = args[1]
            args = args[2:]
        else:
            print 'Unknown argument: %r' % args[0]
            args = args[1:]
    

    Disclaimer: Not tested in any way.