java呼叫python的幾種用法如下:- 在java類中直接執行python語句
- 在java類中直接呼叫本地python指令碼
- 使用Runtime.getRuntime()執行python指令碼檔案(推薦)
- 呼叫python指令碼中的函式
準備工作:建立maven工程,結構如下:
到官網https://www.jython.org/download.html下載Jython的jar包
或者在maven的pom.xml檔案中加入如下程式碼:
(Jython is a Java implementation of Python, developed to run in Java platforms and use Java classes. The name itself is a tell: Jython=Java+Python.)
- <dependency>
- <groupId>org.python</groupId>
- <artifactId>jython-standalone</artifactId>
- <version>2.7.0</version>
- </dependency>
複製代碼
1.在java類中直接執行python語句建立JavaRunPython.java類:
- package com.test;
- import org.python.util.PythonInterpreter;
- public class JavaRunPython {
- public static void main(String[] args) {
- PythonInterpreter interpreter = new PythonInterpreter();
- interpreter.exec("a='hello world'; ");
- interpreter.exec("print a;");
- }
- }
複製代碼 輸出結果如下:
出現的console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.並不是錯誤,而是相容所導致,解決方法如下:
2.在java中直接呼叫python指令碼在本地的D盤建立一個python指令碼,檔名字為javaPythonFile.py,檔案內容如下:
- a = 1
- b = 2
- print (a + b)
複製代碼 建立JavaPythonFile.java類,內容如下:
- package com.test;
-
- import org.python.util.PythonInterpreter;
-
- public class JavaPythonFile {
-
- public static void main(String[] args) {
- PythonInterpreter interpreter = new PythonInterpreter();
- interpreter.execfile("D:\\javaPythonFile.py");
- }
- }
複製代碼 輸出結果如下:
3.使用Runtime.getRuntime()執行python指令碼檔案,推薦使用在本地的D盤建立一個python指令碼,檔名字為Runtime.py,檔案內容如下:
建立RuntimeFunction.java類,內容如下:
- package com.test;
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
-
- public class RuntimeFunction {
- public static void main(String[] args) {
- Process proc;
- try {
- proc = Runtime.getRuntime().exec("python D:\\Runtime.py");
- BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- String line = null;
- while ((line = in.readLine()) != null) {
- System.out.println(line);
- }
- in.close();
- proc.waitFor();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
複製代碼 執行結果如下:
4.呼叫python指令碼中的函式在本地的D盤建立一個python指令碼,檔名字為add.py,檔案內容如下:
- def add(a,b):
- return a + b
複製代碼 建立Function.java類,內容如下:
- package com.test;
-
- import org.python.core.PyFunction;
- import org.python.core.PyInteger;
- import org.python.core.PyObject;
- import org.python.util.PythonInterpreter;
-
- public class Function {
-
- public static void main(String[] args) {
- 11
- PythonInterpreter interpreter = new PythonInterpreter();
- interpreter.execfile("D:\\add.py");
-
- // 第一個引數為期望獲得的函式(變數)的名字,第二個引數為期望返回的物件型別
- PyFunction pyFunction = interpreter.get("add",PyFunction.class);
- int a = 5,b = 10;
- //呼叫函式,如果函式需要引數,在Java中必須先將引數轉化為對應的“Python型別”
- PyObject pyobj = pyFunction.__call__(new PyInteger(a),new PyInteger(b));
- System.out.println("the anwser is: " + pyobj);
- }
-
- }
複製代碼
執行結果如下:
|