java调用python的几种用法如下:

创建maven工程

  1. <dependency>
  2. <groupId>org.python</groupId>
  3. <artifactId>jython-standalone</artifactId>
  4. <version>2.7.0</version>
  5. </dependency>

在java类中直接执行python语句

创建JavaRunPython.java类:

  1. import org.python.util.PythonInterpreter;
  2. public class JavaRunPython {
  3. public static void main(String[] args) {
  4. PythonInterpreter interpreter = new PythonInterpreter();
  5. interpreter.exec("a='hello world'; ");
  6. interpreter.exec("print a;");
  7. }
  8. }

在java类中直接调用本地python脚本

  1. import org.python.util.PythonInterpreter;
  2. public class JavaPythonFile {
  3. public static void main(String[] args) {
  4. PythonInterpreter interpreter = new PythonInterpreter();
  5. interpreter.execfile("D:\\PythonFile.py");
  6. }
  7. }

使用Runtime.getRuntime()执行python脚本文件(推荐)

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. public class RuntimeFunction {
  5. public static void main(String[] args) {
  6. Process proc;
  7. try {
  8. proc = Runtime.getRuntime().exec("python D:\\Runtime.py");
  9. BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  10. String line = null;
  11. while ((line = in.readLine()) != null) {
  12. System.out.println(line);
  13. }
  14. in.close();
  15. proc.waitFor();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. }

调用python脚本中的函数

在本地的D盘创建一个python脚本,文件名字为add.py,文件内容如下:

  1. def add(a,b):
  2. return a + b
  1. import org.python.core.PyFunction;
  2. import org.python.core.PyInteger;
  3. import org.python.core.PyObject;
  4. import org.python.util.PythonInterpreter;
  5. public class Function {
  6. public static void main(String[] args) {
  7. PythonInterpreter interpreter = new PythonInterpreter();
  8. interpreter.execfile("D:\\add.py");
  9. // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
  10. PyFunction pyFunction = interpreter.get("add", PyFunction.class);
  11. int a = 5, b = 10;
  12. //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
  13. PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
  14. System.out.println("the anwser is: " + pyobj);
  15. }
  16. }