匯總java調(diào)用python方法
本文為大家分享了java調(diào)用python方法,供大家參考,具體內(nèi)容如下
一、在java類中直接執(zhí)行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
}
調(diào)用的結(jié)果是Tue,在控制臺顯示出來,這是直接進(jìn)行調(diào)用的。
二、在java中調(diào)用本機python腳本中的函數(shù)
首先建立一個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
}
得到的結(jié)果是:anwser = 2012
三、使用java直接執(zhí)行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類,調(diào)用這個腳本:
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
}
得到的結(jié)果是:
hello [3, 5, 2, 0, 6] [0, 2, 3, 5, 6] [0, 2, 3, 5, 6, 0] 2 3
以上就是三種java調(diào)用python方法,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
使用Logback設(shè)置property參數(shù)方式
這篇文章主要介紹了使用Logback設(shè)置property參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

