Java呼叫Python指令碼
阿新 • • 發佈:2022-05-17
Jython主頁:http://www.jython.org/
Jython是Python語言在Java平臺的實現,本質上,Jython是由Java編寫,其是在JVM上實現的Python語言。因此,可以直接通過Jython在Java中呼叫Python。
引入jython依賴
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version> </dependency>
Example
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
//執行python
interpreter.exec("print (10086)");
}
Run Python File demo.py
// init PythonInterpreter PythonInterpreter interpreter = newPythonInterpreter(); // catch File Exception try{ InputStream filepy = new FileInputStream("D:xxx.py"); // run python file interpreter.execfile(filepy); }catch (Exception e){ e.printStackTrace(); }finally { interpreter.close(); }
獲取函式名
//獲取函式名test PyFunction pyf = inter.get("test", PyFunction.class); //向函式中傳遞引數並獲取返回結果 PyObject res = pyf.__call__(Py.newInteger(2), Py.newInteger(3)); System.out.print(res); inter.cleanup(); inter.close();