目錄
Jython
簡介
Jython(原 JPython),是一個用 Java 語言寫的 Python 解釋器。Jython 程序可以和 Java 無縫集成。除了一些標準模塊,Jython 使用 Java 的模塊。
Jython 幾乎擁有標準的 Python 中不依賴於 C 語言的全部模塊。比如,Jython 的用戶界面將使用 Swing,AWT 或者 SWT。Jython 可以被動態或靜態地編譯成 Java 字節碼。
Jython 還包括 jythonc,一個將 Python 代碼轉換成 Java 代碼的編譯器。這意味着 Python 程序員能夠將自己用 Python 代碼寫的類庫用在 Java 程序裏。
引入Jython依賴
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
Java調用Python的方式
java中直接執行python語句
public void test() throws Exception {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");
}
java中調用本地python腳本
public void test2() throws Exception {
PythonInterpreter interpreter = new PythonInterpreter();
// 獲取文件的輸入流
InputStream in = getClass().getClassLoader().getResourceAsStream("add.py");
interpreter.execfile(in);
// 使用文件絕對路徑
// interpreter.execfile("D:\\add.py");
// 第一個參數爲期望獲得的函數(變量)的名字,第二個參數爲期望返回的對象類型
PyFunction func = (PyFunction) interpreter.get("add",
PyFunction.class);
int a = 100, b = 100;
//調用函數,如果函數需要參數,在Java中必須先將參數轉化爲對應的“Python類型”
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());
}
# add.py 文件內容
def add(a, b):
return a + b
java中使用Runtime.getRuntime()執行腳本文件(推薦)
- 腳本函數中沒有參數
public void test3() throws Exception {
Process proc;
proc = Runtime.getRuntime().exec("python F:\\ProjectFile\\IDEA\\JPython\\src\\test\\resources\\test2.py");// 執行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();
}
# test2.py
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
2. 腳本函數中有參數
public void test4() throws Exception {
int a = 18;
int b = 23;
String[] args = new String[]{"python", "F:\\ProjectFile\\IDEA\\JPythonAndJMail\\src\\test\\resources\\test3.py", String.valueOf(a), String.valueOf(b)};
Process proc = Runtime.getRuntime().exec(args);// 執行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();
}
# test3.py
import sys
def func(a,b):
return (a+b)
if __name__ == '__main__':
a = []
for i in range(1, len(sys.argv)):
a.append((int(sys.argv[i])))
print(func(a[0],a[1]))
Jython初學者必須會用的三種方式,更多高級用法參照Jython官網