Python和java 如何相互调用

网友投稿 245 2022-11-15

Python和java 如何相互调用

目录1.java调用python的函数2.在java中调用本机python脚本中的函数3.使用java直接执行python脚本

1.Java调用Python的函数

在java类中直接执行python语句

class="highlight">

import org.python.util.PythonInterpreter;

/**

* Created by wjhttp://f 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");

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:单片机串行通信的结构组成及工作原理解析
下一篇:PDIUSBD12芯片的性能特点及实现应用设计
相关文章

 发表评论

暂时没有评论,来抢沙发吧~