在java中呼叫python方法
阿新 • • 發佈:2019-02-07
- import javax.script.*;
- import org.python.util.PythonInterpreter;
- import java.io.*;
- importstatic java.lang.System.*;
- publicclass FirstJavaScript
- {
- publicstaticvoid main(String args[])
- {
- PythonInterpreter interpreter = new PythonInterpreter();
-
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); "
- interpreter.exec("print days[1];");
- }//main
- }
這樣得到的結果是Tue,在控制檯顯示出來,這是直接進行呼叫的。
2.在java中呼叫本機python指令碼中的函式:
首先建立一個python指令碼,名字為:my_utils.py
- def adder(a, b):
- return a + b
然後建立一個java類,用來測試,
java類程式碼 FirstJavaScript:
- import javax.script.*;
-
import org.python.core.PyFunction;
- import org.python.core.PyInteger;
- import org.python.core.PyObject;
- import org.python.util.PythonInterpreter;
- import java.io.*;
- importstatic java.lang.System.*;
- publicclass FirstJavaScript
- {
- publicstaticvoid main(String args[])
- {
-
PythonInterpreter interpreter = new PythonInterpreter();
- interpreter.execfile("C:\\Python27\\programs\\my_utils.py");
- PyFunction func = (PyFunction)interpreter.get("adder",PyFunction.class);
- int a = 2010, b = 2 ;
- PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
- System.out.println("anwser = " + pyobj.toString());
- }//main
- }
得到的結果是:anwser = 2012
3.使用java直接執行python指令碼,
建立指令碼inputpy
- #open files
- print'hello'
- number=[3,5,2,0,6]
- print number
- number.sort()
- print number
- number.append(0)
- print number
- print number.count(0)
- print number.index(5)
建立java類,呼叫這個指令碼:
- import javax.script.*;
- import org.python.core.PyFunction;
- import org.python.core.PyInteger;
- import org.python.core.PyObject;
- import org.python.util.PythonInterpreter;
- import java.io.*;
- importstatic java.lang.System.*;
- publicclass FirstJavaScript
- {
- publicstaticvoid main(String args[])
- {
- PythonInterpreter interpreter = new PythonInterpreter();
- interpreter.execfile("C:\\Python27\\programs\\input.py");
- }//main
- }
得到的結果是:
- hello
- [3, 5, 2, 0, 6]
- [0, 2, 3, 5, 6]
- [0, 2, 3, 5, 6, 0]
- 2
- 3