java呼叫python
阿新 • • 發佈:2020-10-18
在java中直接執行python語句
新增maven依賴
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.1</version>
</dependency>
Jython 是一種完整的語言,而不是一個 Java 翻譯器或僅僅是一個 Python 編譯器,它是一個 Python 語言在 Java 中的完全實現。 Jython 也有很多從 CPython 中繼承的模組庫。最有趣的事情是 Jython 不像 CPython 或其他任何高階語言,它提供了對其實現語言的一切存取。所以 Jython 不僅給你提供了 Python 的庫,同時也提供了所有的 Java 類。這使其有一個巨大的資源庫。
public class JavaRunPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print(len(a));"); // 11
}
}
在java中執行python指令碼
指令碼內容
def my_sum(a,b): return a + b print(my_sum(5,8))
java呼叫
public class JavaRunPython2 {
public static void main(String[] args) throws FileNotFoundException {
InputStream is = new FileInputStream("D:/pyutil.py");
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(is);
}
}
通過Runtime呼叫python指令碼
public class RuntimeFunction { public static void main(String[] args) throws Exception { //具體的python安裝路徑 String pythonPath = "C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python38\\python"; Process proc = new ProcessBuilder().command(Arrays .asList(pythonPath, "D:\\pyutil.py")).start(); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); } }
總結
雖然在Java中呼叫Python可以有多種方式解決,甚至因為Jython的出現更顯得非常便利。但是這種程式間巢狀呼叫的方式不可取,首先拋開呼叫效能不說,增加了耦合複雜度。更加有效的方式應該是通過RCP或者RESTful介面進行解耦,這樣各司其職,也便於擴充套件,良好的架構是一個專案能夠健康發展的基礎。在微服務架構大行其道的今天,這種程式間巢狀呼叫的方式將會逐漸被淘汰。