简体   繁体   中英

Java Code with Jython Script

I am working on a Java application in which I have a Jython script written to perform a task.The code works fine and the Jython script executes when it is executed through Eclipse IDE. But when I export the Java application to .jar file the Jython script doesn't run.

This is the directory structure I am following in Eclipse IDE:

application.jar
   |-- com
       |--example

           |-- package1
             |-- Function2.Java
             |-- pre_myAction.py

           |-- package2
             |-- Function1.Java

I am trying to call the script_function from the Function1.java in the following way:

PythonInterpreter interp = new PythonInterpreter();
interp.execfile(".//com//example//pre_myAction.py");
String funcName = "function1";
PyObject someFunc = interp.get(funcName);

if (someFunc == null) {
  throw new Exception("Could not find Python function: " + funcName);
}

try {
   interp.set("DataMap", dataMap);
   someFunc.__call__(new PyString(file1));
  } catch (PyException e1) {
    LOGGER.log(Level.SEVERE, e1.getMessage());
}

interp.cleanup();
interp.close();

When I tried to execute the jar from the command prompt I am getting this error:

File not found -//com//example//pre_myAction.py

And the same code gets executed in Eclipse IDE without any error.

Can anyone provide the solution or suggestion on how to execute the jython script with in a jar file.

A quick browser through the Jython code and it looks like PythonInterpreter.execfile(String) will look for the file in the filesystem, not the JAR. You can try looking it up using Class.getResourceAsStream and using the InputStream version of the method.

It looks like Jython will load files from the root of the JAR automatically, which gives behavior mirroring CPython. See Bundling python files inside jar for access via jython for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM