Python和java相互调用
小疯子 人气:01.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"); }
加载全部内容