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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

Wintersee   2022-12-08 我要评论

概览

因工作场景,需要在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.

总结

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们