Wednesday, 9 December 2015

Java - Call python script functions from java code

Sample Program:

Java Code: SampleJsTest .java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class SampleJsTest {

public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {

//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();

//create a PythonScript engine
ScriptEngine engine = manager.getEngineByName("python");

engine.eval(Files.newBufferedReader(Paths.get("C:\\eclipse\\SamplePythonProject\\TestModule.py"), StandardCharsets.UTF_8));

Invocable inv = (Invocable)engine;
int a = (int) inv.invokeFunction("add", '3', '2');
System.out.println(">>>"+a);
}
}

Python script: TestModule.py
def add(c, d):
    a = int(c)+int(d)
    return a;







Execute the java code.

Place jython-standalone-<<version>>.jar in build path, to avoid the run time exception.

Download "jython-standalone-<<version>>.jar" from http://www.jython.org/downloads.html




Now set the java build path for downloaded jar file.




Now execute the java code again.


To avoid error message "console: Failed to install" displayed in console.
Add the "VM agruments" as "-Dpython.console.encoding=UTF-8", and re-execute the program again.




Note:
For executing the python script function from java code using above procedure, doesn't require python software installed on your machine.

3 comments:

  1. Thanks for the article. It saved my day.

    ReplyDelete
  2. Thanks for the information - it worked !!

    ReplyDelete
  3. hi i your post is really helpful can you tell me how to read class and then fuction from the class?

    ReplyDelete