gpt4 book ai didi

java - jpype 简单 jar 导入并运行 main()

转载 作者:行者123 更新时间:2023-11-28 20:55:52 25 4
gpt4 key购买 nike

我试图打开一个 jar 文件并执行它的主要功能,但 jpype 抛出了一个对我来说没有意义的错误。这是我的代码:

jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.class.path="%s"' % jar)
CommandLine = jpype.JPackage('phylonet').coalescent.CommandLine
CommandLine.main(['-i', input_file, '-o', output_file])
jpype.shutdownJVM()

我得到这个错误:类型错误:包 phylonet.coalescent.CommandLine.main 不可调用

我已经提供了 jar 文件的绝对路径,并且我已经从 META-INF/MANIFEST.MF 中获得了主要功能:

cat tmp/META-INF/MANIFEST.MF | grep Main-Class
Main-Class: phylonet.coalescent.CommandLine

我尝试打开的 jar 文件名为 astral,来自此处:https://github.com/smirarab/ASTRAL

像这样调用它会按预期工作:

java -Djava.class.path="./astral.jar"

那么当我用 jpype 调用它时为什么不呢?

最佳答案

首先,我已经在我自己的 jarfile 上测试了您的代码。事实上,我遇到了这样的错误:

TypeError: Package clip.frontend.Start.main is not Callable

然后,仔细阅读文档后,我使用了另一种方法。

import jpype

# I've used other set of parameters to JVM, and modified a bit your classpath setting.
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=clip.jar")

# Second difference, I decided to use JClass because it was more clear for me.
# Parameter array was kept empty.
jpype.JClass("clip.frontend.Start").main([])
jpype.shutdownJVM()

输出是正确的:

% python2 main.py
2 2
+>+[<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>>+<<<<<<<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]
<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>>++
[<<<<<+>>>>>>>>>>>>+<<<<<<<-]<<<<<[>>>>>+<<<<<-]>>>>>>>>>>>>>[>>]+<<[<<]>[>[>>]
<+<[<<]>-]<<<<<<<[-]++[<<<<<+>>>>>>>>>>>>+<<<<<<<-]<<<<<[>>>>>+<<<<<-]>>>>>>>>>>>>>
[>>]+<<[<<]>[>[>>]<+<[<<]>-]<<<<<<<[-]#JVM has been shutdown

现在,我决定翻译我的解决方案来匹配您的问题:

import jpype
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=astral.jar")
jpype.JClass("phylonet.coalescent.CommandLine").main([])
jpype.shutdownJVM()

并且代码工作正常。比实际解决方案更重要的是,为什么您的代码不起作用。您使用了错误的参数集并以其他方式指定了类路径。

用 JPackage 替换 JClass,代码仍然有效。

import jpype
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=astral.jar")
jpype.JPackage('phylonet').coalescent.CommandLine.main([])
jpype.shutdownJVM()

由于您从类路径中提取类的方式是正确的,唯一可能的原因是指定了无效的参数集。删除 -ea 后代码仍然有效,所以你犯的错误在于这段代码。

'-Djava.class.path="%s"' % jar

事实上,我用这个来反对我的回答,砰,代码产生了这个:

TypeError: Package phylonet.coalescent.CommandLine.main is not Callable

这意味着,参数包含以下内容:

-Djava.class.path="astral.jar"

而不是跟随

-Djava.class.path=astral.jar

引号放错了位置并引发了结果错误。

关于java - jpype 简单 jar 导入并运行 main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com