Different / better approaches for calling python function from Java

前端 未结 2 1239
鱼传尺愫
鱼传尺愫 2020-12-21 06:22

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

My primary requirements are these:

  • call should be transparent, in the sens
相关标签:
2条回答
  • 2020-12-21 06:58

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

    0 讨论(0)
  • 2020-12-21 07:12

    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!

    0 讨论(0)
提交回复
热议问题