Calling a jar file from Python using JPype-total newbie query

狂风中的少年 提交于 2019-12-23 01:11:14

问题


So I have been using subprocess.call to run a jar file from Python as so:

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

where it writes the result to an external output_file file. and -a is an option.

I now want to analyse output_file in python but want to avoid opening the file again. So I want to run jarFile.jar as a Python function, like:

output=jarFile(input_file)

I have installed JPype and got it working, I have set the class path and started the JVM environment:

import jpype

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

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

and am now stuck...


回答1:


java -jar jarFile.jar executes the main method of a class file that is configured in the jar's manifest file. You find that class name if you extract the jar file's META-INF/MANIFEST.MF (open the jar with any zip tool). Look for the value of Main-Class. If that's for instance com.foo.bar.Application you should be able to call the main method like this

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

(I'm not sure about the correct use of the tempfile module, please check yourself)



来源:https://stackoverflow.com/questions/26181553/calling-a-jar-file-from-python-using-jpype-total-newbie-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!