Search code examples
pythonjarjpype

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


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...


Solution

  • 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)