搜尋
首頁後端開發Python教學java後端如何調python接口

java後端如何調python接口

Jul 01, 2019 am 09:42 AM
python

最近在做项目的时候,需要java 调用 python 接口,在网上找了一些方法,但是总碰到一些问题,索性将网上的方法和自己的理解总结一下,希望对各位有所帮助,也请各位大神不吝赐教。

java後端如何調python接口

此方法需要引用 org.python包,需要下载Jpython。在这里先介绍一下Jpython。下面引入百科的解释:(推荐学习:Python视频教程

Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。Jython也有很多从CPython中继承的模块库。最有趣的事情是Jython不像CPython或其他任何高级语言,它提供了对其实现语言的一切存取。所以Jython不仅给你提供了Python的库,同时也提供了所有的Java类。这使其有一个巨大的资源库。

一:创建环境 Python 环境

import org.python.util.PythonInterpreter;

import java.util.Properties;

/**
 * Jython环境,获取Python的实例
 * @author webim
 *
 */
public class JythonEnvironment {

    //定义一个静态变量
    private static JythonEnvironment INSTANCE = new JythonEnvironment();

    /**
     * 私有构造方法
     */
    private JythonEnvironment()
    {
    }

    /**
     * 获取单例
     * @return JythonEnvironment
     */
    public static JythonEnvironment getInstance()
    {
        return INSTANCE;
    }

    /**
     * 获取python解释器
     * @return PythonInterpreter
     */
    public PythonInterpreter getPythonInterpreter()
    {
        Properties props = new Properties();
        props.put("python.home","path to the Lib folder");
        props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
        props.put("python.import.site","false");

        Properties preprops = System.getProperties();
        //对 python 进行初始化
        PythonInterpreter.initialize(preprops, props, new String[0]);
        PythonInterpreter inter = new PythonInterpreter();
        return inter;
    }

}

二:调用 python 的接口

因为 python 和 java是两种不同的语言,因此在项目的 controller 、service 和 mapper 中直接出现 Python 的接口,因此自己封装ExecPython   类,
封装python的接口,目的让 python 接口和java程序分隔开。

import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

/*enum的这个用法,可以作为变种的安全单例,值得借鉴哦 ^_^ */
@Service
@Component
public class ExecPython {

    public static final Logger logger = LoggerFactory.getLogger(Exception.class);

    //定义 python 解释器
    private static PythonInterpreter inter;

    public ExecPython() {
        this.inter  = JythonEnvironment.getInstance().getPythonInterpreter();
        this.inter.execfile("C:\\test.py");
    }

    //设置 python 脚本的路径
    public void setPythonPath (String pythonPath){
        this.inter.execfile(pythonPath);
    }



    public void execute(String scriptFile, Map<string> properties)
    {
        logger.info("获取解释器");
        try
        {

            PyFunction getNetInfo = (PyFunction) inter.get("getNetInfo", PyFunction.class);
            PyObject netInfo = getNetInfo.__call__();
            System.out.println("anwser = " + netInfo.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.info("Python 脚本文件执行失败");
        }
    }

    //获取 Python 字符串
    public String getString(){
//获取到python 脚本中的接口
        PyFunction func = (PyFunction) inter.get("adder", PyFunction.class);
        PyObject pyobj = func.__call__();
        System.out.println("anwser = " + pyobj.toString());
        return pyobj.toString();
    }
    // 获取当前数组
    public String getArr() {
        PyFunction getArr = (PyFunction) inter.get("getArr", PyFunction.class);
        PyObject pyobjTwo = getArr.__call__();
        pyobjTwo.__len__();
        System.out.println("anwser = " + pyobjTwo.toString()+" len:"+pyobjTwo.__len__());

        //将 PyObject 对象转换成 java  对象
        //Object object = pyobjTwo.__tojava__(List.class);
        //List<string> list = (List<string>) object;

        //将查询到数据转换成一个 JSON 字符串
        String result = pyobjTwo.toString();
        String JsonStr = "{" + result + "}";
        logger.info(JsonStr);
        logger.info("将查询的结果转换成 JSON 字符串:",JsonStr);

        return pyobjTwo.toString();
    }
}</string></string></string>

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上是java後端如何調python接口的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python中的合併列表:選擇正確的方法Python中的合併列表:選擇正確的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入兩個列表?如何在Python 3中加入兩個列表?May 14, 2025 am 12:09 AM

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

Python串聯列表字符串Python串聯列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

Python執行,那是什麼?Python執行,那是什麼?May 14, 2025 am 12:06 AM

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python:關鍵功能是什麼Python:關鍵功能是什麼May 14, 2025 am 12:02 AM

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具