使用JPype-total newbie query从Python调用jar文件

时间:2014-10-03 15:04:17

标签: python jar jpype

所以我一直在使用subprocess.call从Python运行 jar 文件:

subprocess.call(['java','-jar','jarFile.jar',-a','input_file','output_file'])

将结果写入外部output_file文件。和 -a 是一个选项。

我现在想在python中分析output_file但是想避免再次打开文件。所以我想将 jarFile.jar 作为Python函数运行,如:

output=jarFile(input_file)

我安装了JPype并使其正常工作,我已经设置了类路径并启动了JVM环境:

import jpype

classpath="/home/me/folder/jarFile.jar"

jpype.startJVM(jpype.getDefaultJVMPath(),"-Djava.class.path=%s"%classpath)

现在我被困了......

1 个答案:

答案 0 :(得分:0)

java -jar jarFile.jar执行在jar manifest file中配置的类文件的main方法。 如果解压缩jar文件META-INF/MANIFEST.MF,则会找到该类名(使用任何zip工具打开jar)。寻找Main-Class的价值。如果那是例如com.foo.bar.Application你应该能够像这样调用主要方法

def jarFile(input_file):
    # jpype is started as you already did
    assert jpype.isJVMStarted()
    tf = tempfile.NamedTemporaryFile()
    jpype.com.foo.bar.Application.main(['-a', input_file, tf.name])
    return tf

(我不确定是否正确使用了tempfile模块,请自行检查)