Question

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?

Was it helpful?

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.

OTHER TIPS

The getopt library is bundled with Jython 2.1. It's not as fancy as the newer argument parsing modules, but still much better than rolling your own argument parsing.

import getopt

Documentation for getopt: http://docs.python.org/release/2.1.1/lib/module-getopt.html

I'm using it under WebSphere Appserver 7.0.0.x. I see you've tagged this question with websphere-6.1 - unfortunately I don't have a WAS 6.1 system at hand to test right now.

EDIT: Verified on WebSphere 6.1; getopt is present.

Note that most libraries are actually simple Python modules that you can find under \Lib in your Python distribution, so often a simple file copy will give you the library.

In this case, I copied optparse.py (with its dependency textparse.py) from Python 2.7 to Jython 2.2, and it seems to import just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top