Python调用Jar包的两种方式小结
作者:Wintersee 时间:2023-07-26 06:29:12
概览
因工作场景,需要在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.
来源:https://blog.csdn.net/u012386109/article/details/120156736
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
vue实现选项卡及选项卡切换效果
![](https://img.aspxhome.com/file/2023/4/130274_0s.jpg)
成功解决ValueError: Supported target types are:('binary', 'multiclass'). Got 'continuous' instead.
Golang测试框架goconvey进行单元测试流程介绍
解决Python复杂zip文件的解压问题
![](https://img.aspxhome.com/file/2023/9/75329_0s.jpg)
python使用BeautifulSoup分页网页中超链接的方法
解决js相同的正则多次调用test()返回的值却不同的问题
python实现批量获取指定文件夹下的所有文件的厂商信息
Vue.directive 实现元素scroll逻辑复用
![](https://img.aspxhome.com/file/2023/1/130061_0s.png)
整理Python 常用string函数(收藏)
基于B-树和B+树的使用:数据搜索和数据库索引的详细介绍
![](https://img.aspxhome.com/file/2023/9/96189_0s.jpg)
在golang中使用Sync.WaitGroup解决等待的问题
绿色下划线的简洁CSS导航代码
![](https://img.aspxhome.com/file/UploadPic/20079/17/2007917125420230s.jpg)
Python实现端口检测的方法
![](https://img.aspxhome.com/file/2023/0/101720_0s.png)
Python中获取对象信息的方法
Oracle关于时间/日期的操作
浅谈JavaScript编程语言的编码规范
mysql 5.7.11 winx64安装配置方法图文教程
![](https://img.aspxhome.com/file/2023/1/108891_0s.png)
一个NumericStepper组件
![](https://img.aspxhome.com/file/UploadPic/20101/22/num22-95s.png)