Python和java 如何相互调用
时间:2022-08-30 09:30:03|栏目:Python代码|点击: 次
1.Java调用Python的函数
在java类中直接执行python语句
class="highlight">
import org.python.util.PythonInterpreter;
/**
* Created by wjf on 2018/3/16.
*/
public class java2python {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("# coding=utf-8");
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");
}
}
2.在java中调用本机python脚本中的函数
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:\\Users\\wjf\\IdeaProjects\\javaTestPython\\src\\my_utils.py");
PyFunction func = interpreter.get("adder", PyFunction.class);
int a = 2010, b = 8;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());
}
3.使用java直接执行python脚本
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:\\Users\\wjf\\IdeaProjects\\javaTestPython\\src\\input.py");
}






