java调用python的几种用法如下:
- 在java类中直接执行python语句
- 在java类中直接调用本地python脚本
- 使用Runtime.getRuntime()执行python脚本文件(推荐)
- 调用python脚本中的函数
准备工作:
创建maven工程,结构如下:
到官网https://.test;import org.python.core.PyFunction;import org.python.core.PyInteger;import org.python.core.PyObject;import org.python.util.PythonInterpreter;public class Function { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("D:\\add.py"); // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型 PyFunction pyFunction = interpreter.get("add", PyFunction.class); int a = 5, b = 10; //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型” PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); System.out.println("the anwser is: " + pyobj); }}
运行结果如下:
到此这篇关于详解java调用python的几种用法(看这篇就够了)的文章就介绍到这了,更多相关java调用python内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!