溫馨提示×

java中怎么調(diào)用python腳本

小億
351
2024-06-04 10:08:21
欄目: 編程語言

在Java中調(diào)用Python腳本可以使用以下幾種方法:

  1. 使用Runtime類的exec方法執(zhí)行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類執(zhí)行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中執(zhí)行:

首先需要在項目中引入Jython庫,然后可以直接在Java代碼中調(diào)用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中調(diào)用Python腳本的幾種常用方法,可以根據(jù)具體需求選擇適合的方法。

0