概览

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

  1. java -jar xx.jar
  2. JPype

环境配置

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

  1. 安装JDK

    主要有三种方式: 1. 通过yum源安装 2. rpm安装 3. 解压JDK安装包手动安装

    第一种方式需要联网或者配置内网的yum源,第三种方式比较繁琐且需要配置环境变量,相较而言第二种方式比较适合我这一次的场景。具体安装细节不再赘述,详情可参考这篇博文:CentOS安装jdk的几种方法及配置环境变量

  2. 安装JPype(如需要)

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

    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

  1. 具体的使用场景和方法,可参考Github里的UserGuide

  2. 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.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐