栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA——java服务调用python脚本服务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA——java服务调用python脚本服务

摘要

在日常的开发过程中我们经常遇到的java调用python的脚本,所以在本博文中我将为大家展示java项目的dokcer调用python服务的docker项目,同样在java调用其他语言的时候也是同样的一个道理。以下的例子仅仅工大家参考。

项目结构

项目代码
package com.xjl.javatopython.function;

import org.python.core.*;
import org.python.util.PythonInterpreter;


public class JavaCallPython {
    //解释器
    private PythonInterpreter pythonInterpreter;

    public PythonInterpreter getPythonInterpreter(String pythonfile) {
        PythonInterpreter pythonInterpreter = new PythonInterpreter();
        pythonInterpreter.execfile(pythonfile);
        return pythonInterpreter;
    }

    public void setPythonInterpreter(PythonInterpreter pythonInterpreter) {
        this.pythonInterpreter = pythonInterpreter;
    }

    
    public void calllpython_name(PythonInterpreter interpreter) {
        PyObject xyzobj = interpreter.get("xyz");
        System.out.println("xyz=" + xyzobj);
        PyObject abcobj = interpreter.get("abc");
        System.out.println("abc=" + abcobj);
        interpreter.set("newstr", "newString");//手动添加newstr变量
        System.out.println("newstr=" + interpreter.get("newstr"));
        interpreter.exec("print('='*50)");
    }

    
    public void calllpython_function(PythonInterpreter interpreter) {
        PyFunction funStr = interpreter.get("func_str", PyFunction.class);
        System.out.println(funStr.__call__().__tojava__(PyString.class));
        System.out.println(funStr.__call__());
        PyFunction funList = interpreter.get("func_list", PyFunction.class);
        PyList list = (PyList) funList.__call__().__tojava__(PyList.class);
        System.out.println(list);
        System.out.println(list.get(2));
        PyFunction funDict = interpreter.get("func_dict", PyFunction.class);
        PyDictionary dict = (PyDictionary) funDict.__call__().__tojava__(PyDictionary.class);
        System.out.println(dict);
        System.out.println(dict.get(2));
    }

    public static void main(String[] args) {
        String python_path = "Java_To_Python/src/main/resources/scripts/test.py";
        JavaCallPython testCallPython_jython = new JavaCallPython();
        PythonInterpreter pythonInterpreter = testCallPython_jython.getPythonInterpreter(python_path);
        testCallPython_jython.calllpython_name(pythonInterpreter);
        testCallPython_jython.calllpython_function(pythonInterpreter);
    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/275251.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号