hello world
在resource/py文件夹下创建一个python脚本,文件名字为test.py,文件内容如下:
a = 1b = 2print (a + b)
创建JavaPythonFile.java类,内容如下:

package com.et.python.util;import org.python.util.PythonInterpreter;public class JavaPythonFile { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("D:\\IdeaProjects\\ETFramework\\python\\src\\main\\resources\\py\\test.py"); }}
实行结果
3
在resource/py文件夹下创建一个python脚本,文件名字为runtime.py,文件内容如下:
print('RuntimeDemo')
java调用代码如下
package com.et.python.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class RuntimeFunction { public static void main(String[] args) { Process proc; try { proc = Runtime.getRuntime().exec("python D:\\IdeaProjects\\ETFramework\\python\\src\\main\\resources\\py\\runtime.py"); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}
实行结果
RuntimeDemo
在resource/py文件夹下创建一个python脚本,文件名字为add.py,文件内容如下:
def add(a,b): return a + b
创建Function.java类,内容如下:
package com.et.python.util;import org.python.core.PyFunction;import org.python.core.PyInteger;import org.python.core.PyObject;import org.python.util.PythonInterpreter;public class Function { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("D:\\IdeaProjects\\ETFramework\\python\\src\\main\\resources\\py\\add.py"); // 第一个参数为期望得到的函数(变量)的名字,第二个参数为期望返回的工具类型 PyFunction pyFunction = interpreter.get("add", PyFunction.class); int a = 5, b = 10; //调用函数,如果函数须要参数,在Java中必须先将参数转化为对应的“Python类型” PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); System.out.println("the anwser is: " + pyobj); }}
实行结果
the anwser is: 15