Python和java相互调用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python和java相互调用

小疯子   2022-05-23 我要评论

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");
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们