Calling Python in Java?

2019-01-01 05:16发布

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?

9条回答
低头抚发
2楼-- · 2019-01-01 05:26

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.

查看更多
闭嘴吧你
3楼-- · 2019-01-01 05:26

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

查看更多
还给你的自由
4楼-- · 2019-01-01 05:27

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

查看更多
千与千寻千般痛.
5楼-- · 2019-01-01 05:34

You can call any language from java using Java Native Interface

查看更多
初与友歌
6楼-- · 2019-01-01 05:35

Depending on your requirements, options like XML-RPC could be useful, which can be used to remotely call functions virtually in any language supporting the protocol.

查看更多
裙下三千臣
7楼-- · 2019-01-01 05:36

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.

查看更多
登录 后发表回答