使用Runtime.getRuntime()執行python腳本文件
在本地的D盤創建一個python腳本,文件名字為Runtime.py,文件內容如下:
print('RuntimeDemo')
注意:如果Python腳本里面有文件路徑,則要進行轉換,比如 ./ 指的是javaweb項目的當前項目路徑,而不是Python腳本的當前路徑。
創建RuntimeFunction.java類,內容如下:
1 package com.test; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 public class RuntimeFunction { 8 public static void main(String[] args) { 9 Process proc; 10 try { 11 proc = Runtime.getRuntime().exec("python D:\\Runtime.py"); 12 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); 13 String line = null; 14 while ((line = in.readLine()) != null) { 15 System.out.println(line); 16 } 17 in.close(); 18 proc.waitFor(); 19 } catch (IOException e) { 20 e.printStackTrace(); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 } 25 }
運行結果如下:
調用python腳本中的函數
在本地的D盤創建一個python腳本,文件名字為add.py,文件內容如下:
def add(a,b): return a + b
創建Function.java類,內容如下:
1 package com.test; 2 3 import org.python.core.PyFunction; 4 import org.python.core.PyInteger; 5 import org.python.core.PyObject; 6 import org.python.util.PythonInterpreter; 7 8 public class Function { 9 10 public static void main(String[] args) { 11 PythonInterpreter interpreter = new PythonInterpreter(); 12 interpreter.execfile("D:\\add.py"); 13 14 // 第一個參數為期望獲得的函數(變量)的名字,第二個參數為期望返回的對象類型 15 PyFunction pyFunction = interpreter.get("add", PyFunction.class); 16 int a = 5, b = 10; 17 //調用函數,如果函數需要參數,在Java中必須先將參數轉化為對應的“Python類型” 18 PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); 19 System.out.println("the anwser is: " + pyobj); 20 } 21 22 }
運行結果如下:
中文亂碼問題解決
用Runtime.getRuntime.exec()調用Python腳本時,Java端捕獲腳本有中文輸出時,輸出的中文可能會是亂碼,因為Python安裝在Windows環境下的默認編碼格式是GBK。
解決方法:
在被調用的腳本的開頭增加如下代碼,一定要添加到其他依賴模塊import之前:
import io import sys sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
參考文章: