Friday, 25 September 2015

Python vs. Jython - The case of the mysterious argument ...

I'm writing a Jython script to manage IBM BPM security roles, as I mentioned previously: -


when I discovered that Jython and Python treat command-line arguments differently.

So here's two scripts: -

foo.py

#!/usr/bin/python

import sys

a = sys.argv[0]
b = sys.argv[1]
c = sys.argv[2]

print a + " " + b + " " + c


bar.py

#!/usr/bin/python

import sys

a = sys.argv[1]
b = sys.argv[2]
c = sys.argv[3]

print a + " " + b + " " + c


and here's what happens when I run each of them in Python: -

python foo.py Hello World !

foo.py Hello World

python bar.py Hello World !

Hello World !

And now here's what happens when I run each of them in Jython: -

/opt/IBM/WebSphere/AppServer/bin/wsadmin.sh -conntype none -f foo.py Hello World !

WASX7357I: By request, this scripting client is not connected to any server process. Certain configuration and application operations will be available in local mode.
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: "[Hello, World, !]"

Hello World !

/opt/IBM/WebSphere/AppServer/bin/wsadmin.sh -conntype none -f bar.py Hello World !

WASX7357I: By request, this scripting client is not connected to any server process. Certain configuration and application operations will be available in local mode.
WASX7303I: The following options are passed to the scripting environment and are available as arguments that are stored in the argv variable: "[Hello, World, !]"
WASX7017E: Exception received while running file "bar.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (innermost last):
  File "<string>", line 7, in ?
IndexError: index out of range: 3

In other words, Python starts counting the arguments from one ( which seems quite logical ), where argument zero is the name of the script.

By contrast, Jython starts counting from zero, hence the exception when I run bar.py i.e. the script looks for an argument indexed 3 whereas it only received arguments 0, 1 and 2 - hence the index out of range error.

Interesting, eh ?

No comments:

Yay, VMware Fusion and macOS Big Sur - no longer "NAT good friends" - forgive the double negative and the terrible pun ...

After macOS 11 Big Sur was released in 2020, VMware updated their Fusion product to v12 and, sadly, managed to break Network Address Trans...