最近在做项目的时候,需要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中文網其他相關文章!

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

Inpython,一個“列表” isaversatile,mutableSequencethatCanholdMixedDatateTypes,而“陣列” isamorememory-sepersequeSequeSequeSequeSequeRingequiringElements.1)列表

pythonlistsandArraysareBothable.1)列表Sareflexibleandsupportereceneousdatabutarelessmory-Memory-Empefficity.2)ArraysareMoremoremoremoreMemoremorememorememorememoremorememogeneSdatabutlesserversEversementime,defteringcorcttypecrecttypececeDepeceDyusagetoagetoavoavoiDerrors。

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

WebStorm Mac版
好用的JavaScript開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

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