共計 1806 個字符,預計需要花費 5 分鐘才能閱讀完成。
在 Java 中調用 Python 模型有幾種方式:
- 使用 Java 的 ProcessBuilder 類來執行 Python 腳本。這種方法通過創建一個新進程來運行 Python 腳本,并通過輸入輸出流進行通信。你可以通過該進程的輸入流傳遞數據給 Python 模型,然后通過讀取進程的輸出流獲取模型的結果。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PythonModelCaller {public static void main(String[] args) {try {// 創建進程并執行 Python 腳本
ProcessBuilder pb = new ProcessBuilder("python", "path/to/your/python/script.py");
Process process = pb.start();
// 獲取進程的輸入流和輸出流
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// 向 Python 腳本傳遞數據
process.getOutputStream().write("Input data".getBytes());
process.getOutputStream().flush();
// 讀取 Python 腳本的輸出
String output;
while ((output = bufferedReader.readLine()) != null) {System.out.println(output);
}
// 等待進程執行完畢
process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();
}
}
}
- 使用 Java 的 Jython 庫。Jython 是一個 Java 實現的 Python 解釋器,它允許在 Java 中直接調用 Python 代碼。你可以將 Python 模型的代碼封裝在一個 Python 腳本中,并在 Java 中使用 Jython 庫來執行該腳本。
首先,將 Jython 庫添加到 Java 項目的依賴中。然后,可以使用以下代碼調用 Python 模型:
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class PythonModelCaller {public static void main(String[] args) {try (PythonInterpreter pyInterp = new PythonInterpreter()) {// 加載 Python 腳本
pyInterp.execfile("path/to/your/python/script.py");
// 獲取 Python 函數對象
PyFunction pyFunction = pyInterp.get("your_function_name", PyFunction.class);
// 調用 Python 函數并傳遞參數
PyObject result = pyFunction.__call__(Py.newString("Input data"));
// 處理 Python 函數的返回值
System.out.println(result);
}
}
}
注意:使用 Jython 庫可能存在一些性能上的限制,因為它是一個解釋器,而不是一個編譯器。
- 使用 Java 的 JNI(Java Native Interface)來調用 Python 模型。這種方法需要在 Java 和 Python 之間編寫一層 C 或 C ++ 的接口,將 Java 數據轉換為 Python 數據,并調用 Python 模型。這種方法比較復雜,但可以提供更高的性能。
以上是三種常見的在 Java 中調用 Python 模型的方法,你可以根據實際情況選擇適合你的方式。
丸趣 TV 網 – 提供最優質的資源集合!
正文完