一、安装
pip3 install jpype1
或
yum install jpype1
如果安装过程中报错:
gcc: error trying to exec 'cc1plus': execvp: No such file or directory
error: command 'gcc' failed with exit status 1
解决办法:
yum install gcc-c++
二、调用java API
新建test.py,代码如下:
from jpype import *
startJVM(getDefaultJVMPath(), "-ea”)
java.lang.System.out.println("Hello World”)
shutdownJVM()
运行test.py
python test.py
三、调用第三方jar包
在com目录下新建文件test.java
package com;
public class Test {
public String run(String str){
return str;
}
}
编译
javac test.py
编译生成test.class文件
python调用
jarpath = os.path.join(os.path.abspath('.'), 'libs/test.class')
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)
Test = jpype.JClass('com.Test')
# 或者通过JPackage引用Test类
# com = jpype.JPackage('com')
# Test = com.Test
t = Test()
res = t.run("a")
print res
jpype.shutdownJVM()
本文档详细介绍了如何安装JPype模块,包括解决安装过程中的常见错误。接着,展示了如何创建并运行代码进行模块调用。最后,解释了如何在项目中编译并调用第三方包。
7498





