Jpype:在jar中导入类时出现ModuleNotFoundError
Posted
技术标签:
【中文标题】Jpype:在jar中导入类时出现ModuleNotFoundError【英文标题】:Jpype: ModuleNotFoundError when import classes in jar 【发布时间】:2021-11-13 13:12:55 【问题描述】:问题
当我将-Djava.class.path
设置为目录"jars/*"
时,我得到了ModuleNotFoundError: No module named 'spoon'
。
项目结构
utils
├── __init__.py
├── jars
│ └── spoon-core-9.2.0-beta-4.jar
└── parse_utils.py
# parse_utils.py
import jpype
import jpype.imports
from jpype.types import *
JARS_PATH = 'jars/*'
jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path=' + JARS_PATH)
import spoon.Launcher as Launcher
我尝试过的
JClass 和 JPackage
我在 *** Jpype import cannot find module in jar 发现了类似的问题,我尝试了最佳答案但失败了。
Launcher = jpype.JPackage('spoon').Launcher # AttributeError: Java package 'spoon' is not valid
Launcher = jpype.JClass('spoon.Launcher') # TypeError: Class spoon.Launcher is not found
Launcher = jpype.JClass("java.lang.Class").forName('spoon.Launcher') # java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: spoon.Launcher
使用jar路径
JARS_PATH = 'jars/spoon-core-9.2.0-beta-4.jar'
我得到了:
Traceback (most recent call last):
File "ClassLoader.java", line 357, in java.lang.ClassLoader.loadClass
File "Launcher.java", line 338, in sun.misc.Launcher$AppClassLoader.loadClass
File "ClassLoader.java", line 424, in java.lang.ClassLoader.loadClass
File "URLClassLoader.java", line 381, in java.net.URLClassLoader.findClass
java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: com.martiansoftware.jsap.JSAPException
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "org.jpype.pkg.JPypePackage.java", line -1, in org.jpype.pkg.JPypePackage.getObject
File "Class.java", line 348, in java.lang.Class.forName
File "Class.java", line -2, in java.lang.Class.forName0
Exception: Java Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/audrey/Documents/GitHub/xiaoven/codegex/utils/parse_utils.py", line 16, in <module>
import spoon.Launcher as Launcher
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 971, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 914, in _find_spec
File "/usr/local/Caskroom/miniconda/base/envs/codegex/lib/python3.8/site-packages/jpype/imports.py", line 194, in find_spec
if not hasattr(base, parts[2]):
java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: com/martiansoftware/jsap/JSAPException
【问题讨论】:
【参考方案1】:见this link:
我会先检查罐子是否在路径中被拾起。
import jpype jpype.startJVM(classpath="jars/*") print(jpype.java.lang.System.getProperty("java.class.path"))
我的猜测是您的测试代码中存在语法错误,或者勺子 jar 缺少一些依赖项,但在您的示例中没有任何突出之处。 jars 目录中是否有所需的 jar 依赖项,包括
com.martiansoftware.jsap.JSAPException
?
我根据错误日志(或IDEA项目视图下的External Libraries
列表)手动下载缺失的jar后,成功导入spoon类。
【讨论】:
以上是关于Jpype:在jar中导入类时出现ModuleNotFoundError的主要内容,如果未能解决你的问题,请参考以下文章
在 Doctrine ORM 2 中加入类表继承时出现“主键 elementId 的缺失值”