1. 程式人生 > >java呼叫python方法總結

java呼叫python方法總結

一、在java類中直接執行python語句

import org.python.util.PythonInterpreter;
public class FirstJavaScript {
    public static void main(String args[]) {

        PythonInterpreter interpreter = new PythonInterpreter();

        interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
        interpreter.exec("print days[1];"
); }// main }

呼叫的結果是Tue,在控制檯顯示出來,這是直接進行呼叫的。

二、在java中呼叫本機python指令碼中的函式

首先建立一個python指令碼,名字為:my_utils.py

def adder(a, b):  
    return a + b  

然後建立一個java類,用來測試,

java類程式碼 FirstJavaScript:

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import
org.python.util.PythonInterpreter;
public class FirstJavaScript { public static void 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

三、使用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 org.python.util.PythonInterpreter;

public class FirstJavaScript {
    public static void main(String args[]) {

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("C:\\Python27\\programs\\input.py");
    }// main
}

得到的結果是:
view plain

hello  
[3, 5, 2, 0, 6]  
[0, 2, 3, 5, 6]  
[0, 2, 3, 5, 6, 0]  
2  
3