Mahesha999
Mahesha999

Reputation: 24801

Different / better approaches for calling python function from Java

I am quite new to python and am trying to call python's function from java.

My primary requirements are these:

There are several options that I found online. Few are:

It seems that Jython PythonInterpreter is the best choice if I have understood all above approaches correctly. Have I made mistakes while grasping them? Also is there any other better option?

Upvotes: 3

Views: 2218

Answers (3)

Steves
Steves

Reputation: 3234

Another option is https://github.com/oracle/graalpython. Java based Python 3 implementation with support for native extensions such as NumPy or Pandas.

Disclaimer: I am one of GraalPy developers.

Upvotes: 0

FloW
FloW

Reputation: 97

@Mahesha999, regarding the ability to stick with CPython which seems important now from your last comment:

Jep is a good option to be able to run python code which uses calls to native, like pandas that you mentionned.

You'll need to write some wrapping code because Jep only implements automatic conversion between Java and Python between the most used types, which pandas.DataFrame is not.

However if your use case is not to complex, you can access your pandas objects as numpy.NDArray object by calling DataFrame.values on your dataframe instance, and Jep implement conversion to the Java class it embeds for NDArray.

You can get back to Java values from python code you execute by using Jep.getValue(String pythonVariableName, Class clazz)

For example

Jep jep = new Jep();
jep.eval("import my_script");
jep.eval("df = my_script.function_returning_a_dataframe()");
jep.eval("col = df.a_column.values");
NDArray myCol = jep.getValue("col", NDArray.class);

I do so on a project I coded in Python that I need to integrate as a plugin in a Java application, so far it works.

Upvotes: 3

holdenweb
holdenweb

Reputation: 37113

There is no current answer to this problem. Using CPython relies on the execution of Python bytecodes, which in turn requires that the Python interpreter be embedded in the execution environment. Since no Java runtime comes with an embedded Python interpreter, it really does look as though Jython is the best answer.

Sometimes the answer you want just isn't available!

Upvotes: 0

Related Questions