Calling Python in Java?

前端 未结 11 1245
北荒
北荒 2020-11-22 13:04

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?

相关标签:
11条回答
  • 2020-11-22 13:29

    Jython has some limitations:

    There are a number of differences. First, Jython programs cannot use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. Although it is technically feasible to support such extensions - IronPython does so - there are no plans to do so in Jython.

    Distributing my Python scripts as JAR files with Jython?

    you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java:

    Running a bash shell script in java

    Running Command Line in Java

    java runtime.getruntime() getting output from executing a command line program

    0 讨论(0)
  • 2020-11-22 13:30

    Here a library that lets you write your python scripts once and decide which integration method (Jython, CPython/PyPy via Jep and Py4j) to use at runtime:

    https://github.com/subes/invesdwin-context-python

    Since each method has its own benefits/drawbacks as explained in the link.

    0 讨论(0)
  • You can call any language from java using Java Native Interface

    0 讨论(0)
  • 2020-11-22 13:41

    GraalVM is a good choice. I've done Java+Javascript combination with GraalVM for microservice design (Java with Javascript reflection). They recently added support for python, I'd give it a try especially with how big its community has grown over the years.

    0 讨论(0)
  • 2020-11-22 13:43

    It's not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).

    Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.

    Updated on Mar 24th 2020: According to @stx's comment, the above approach is not suitable for massive data transfer between client and server. Here is another approach I recommended: Connecting Python and Java with Rust(C/C++ also ok). https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0

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