一.准备
首先我们要准备好以下东西:
- java运行环境
- python运行环境
- Maven中添加下面的内容
<!-- https://mvnrepository.com/artifact/org.python/jython -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.1b3</version>
</dependency>
二.思路
程序都有三个部分:输入,执行操作,输出,所以对于java来说,它需要向一个Python程序输入必要值,然后接收python程序运行的结果就好了.
三.案例
我们举最简单的1+1的例子
Python需要执行的操作类 MyPython.py:
def add_two(a, b):
return a + b
java操作类 Main.java:
package jython_test;
import org.python.core.PyClass;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties props = new Properties();
props.put("python.home", "D:\\Python\\Python36\\Lib");//python的Lib库的位置
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");//注意:如果没有这一条会有Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site报错
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
//python解释器
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\\MyPython.py");//python文件路径
PyFunction function = interpreter.get("add_two", PyFunction.class);//这样得到了指定的函数
PyObject pyobj = function.__call__(new PyInteger(1), new PyInteger(1));//给函数传入参数,这里不会有代码提示,所以要保证参数类型与数量正确,否则会报错
System.out.println(pyobj.toString());
}
}