iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python调用Jar包的两种方式小结
  • 919
分享到

Python调用Jar包的两种方式小结

Python调用Jar包Python调用JarPythonJar包调用 2022-12-08 20:12:35 919人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录概览环境配置安装jdk安装JPype(如需要)调用示例java -jarJPype再多说一点关于JPype总结概览 因工作场景,需要在python代码里调用Jar包来实现一些功能

概览

因工作场景,需要在python代码里调用Jar包来实现一些功能,调研下来主要有两种方式:

  • java -jar xx.jar
  • JPype

环境配置

因为要在公司内网操作,所以需要通过离线方式进行安装。环境用的是一个Centos7.7的Docker镜像。

安装JDK

主要有三种方式:

  • 1. 通过yum源安装
  • 2. rpm安装
  • 3. 解压JDK安装包手动安装

第一种方式需要联网或者配置内网的yum源

第三种方式比较繁琐且需要配置环境变量,相较而言第二种方式比较适合我这一次的场景

具体安装细节不再赘述,详情可参考这篇文章:CentOS安装jdk的几种方法及配置环境变量

安装JPype(如需要)

同样的,可以通过pip直接在线安装,也可以通过Python setup.py install或者pip install xx.whl离线安装,可参考Python安装包的三种方式

JPype安装包和文档可以通过官方GitHub 或者官方PyPi获取。

调用示例

java -jar

import os
import subprocess
import jpype
import time

def query_by_java_jar(jar_path, param):
    execute = "java -jar {} '{}'".fORMat(jar_path, param)
    # print(execute)
    output = subprocess.Popen(execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = output.stdout.readlines()
    return res

JPype

import os
import subprocess
import jpype
import time

def query_by_jpype(jar_path, some_param):
    if not jpype.isJVMStarted():
        jpype.startJVM(classpath=[jar_path])
    if not jpype.isThreadAttachedToJVM():
        jpype.attachThreadToJVM()
    try:
        java_class = jpype.JClass('com.xxx.xxx')
        result = java_class.someStaticFunction(some_param)
    except Exception as e:
        print(e)
        result = None
    finally:
        #jpype.shutdownJVM()
        return result

再多说一点

关于JPype

  • 具体的使用场景和方法,可参考github里的UserGuide
  • shutdown之后再start报错:OSError: JVM cannot be restarted

这是JPype的一个使用限制,为防止内存泄漏的,同一进程内关闭JVM后无法再次启动。

可考虑将调用方法写入到一个Python脚本,然后通过subprocess去调用。

官方解释此处也在贴一下:

JPype Known limitations

Restarting the JVM

JPype caches many resources to the JVM. Those resource are still allocated after the JVM is shutdown as there are still Python objects that point to those resources. If the JVM is restarted, those stale Python objects will be in a broken state and the new JVM instance will obtain the references to these resulting in a memory leak. Thus it is not possible to start the JVM after it has been shut down with the current implementation.

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Python调用Jar包的两种方式小结

本文链接: https://www.lsjlt.com/news/174533.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作