Different / better approaches for calling python function from Java

那年仲夏 提交于 2019-11-29 15:09:51

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!

@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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!