3

I am working on a big Java project, where Jython scripts are interpreted from Java code. For a reason I have not yet figured out, nothing works in the Jython script unless functions, class, variables, are declared all as global. In an attempt to track down this problem, I have narrowed the issue down to this. Below are :

  • A Jython script script.py which runs well when launched with java -jar jython.jar script.py
  • A Java main class Interpreter.java which uses Jython 2.2 methods to try and interpret the Jython script given above

Python script :

#global aFunction # uncommenting this makes the script work from Java

def main():
    aFunction()


def aFunction():
    print 'aFunction() called'


main()

Java class :

import java.io.File;

import org.python.core.PyException;
import org.python.core.PyStringMap;
import org.python.core.PySystemState;


public class Interpreter {

    public static void main(final String[] args) {
        final PyStringMap localNameSpace = new PyStringMap();
        final PyStringMap globalNameSpace = new PyStringMap();

        final File scriptFile = new File("../../jython/script.py");       
        PySystemState.initialize();

        try {
            org.python.core.__builtin__.execfile(scriptFile.getAbsolutePath(), globalNameSpace, localNameSpace);
        } catch (final PyException pyException) {
            pyException.printStackTrace();
        }

    }

}

Here is the error I get when running the Java class.

Traceback (innermost last):
  File "/opt/coflight/axel/workspace/essais/../../jython/script.py", line 12, in ?
  File "/opt/coflight/axel/workspace/essais/../../jython/script.py", line 5, in main
NameError: aFunction

Any ideas on how to correct the Java class so that the interpreter can run the Jython script ? Thanks !

1 Answer 1

3

I can't explain the error that you get, but I was able to make it work by using PythonInterpreter:

org.python.util.PythonInterpreter interp = new org.python.util.PythonInterpreter();
String scriptname = "script.py"; 
interp.execfile(scriptname);
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, that works for me as well ! I guess my application was supposed to use this rather than the call to __builtin__
Is there an option to do the same in scala?
@EdwinVivekN: I'm not sure what you mean. You should ask a new question if you need help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.