java中怎么调用python脚本

1042
2024/5/21 10:08:21
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中调用Python脚本可以使用以下几种方法:

  1. 使用Runtime类的exec方法执行Python脚本:
String command = "python path/to/python/script.py";
Process process = Runtime.getRuntime().exec(command);

BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
    System.out.println(line);
}
input.close();
  1. 使用ProcessBuilder类执行Python脚本:
ProcessBuilder pb = new ProcessBuilder("python", "path/to/python/script.py");
Process process = pb.start();

BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
    System.out.println(line);
}
input.close();
  1. 使用Jython库将Python代码嵌入到Java中执行:

首先需要在项目中引入Jython库,然后可以直接在Java代码中调用Python代码:

import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Main {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("path/to/python/script.py");
        
        PyObject someFunc = interpreter.get("someFunc");
        someFunc.__call__();
    }
}

这些是在Java中调用Python脚本的几种常用方法,可以根据具体需求选择适合的方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python导入模块的方法是什么