41
votes

I have been looking for an answer for how to execute a java jar file through python and after looking at:

Execute .jar from Python

How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?

How to run Python egg files directly without installing them?

I tried to do the following (both my jar and python file are in the same directory):

import os

if __name__ == "__main__":
    os.system("java -jar Blender.jar")

and

import subprocess

subprocess.call(['(path)Blender.jar'])

Neither have worked. So, I was thinking that I should use Jython instead, but I think there must a be an easier way to execute jar files through python.

Do you have any idea what I may do wrong? Or, is there any other site that I study more about my problem?

5
What errors are you getting? Is the PATH env var set correctly? - NullUserException
The path that I am using is copy-paste, so it is inserted correctly. The problem is that I am trying to insert this in a method-function in python, like def blender(): os.system(java -jar Blender.jar) for example, and the IDLE says: Invalid syntax in my method. - Dimitra Micha
I have tried both of them in different ways, using the absolute paths, but always the same mistake. I am using macos - Dimitra Micha
There are no quotes around java -jar Blender. Is that just a copy-and-paste error? - NullUserException
The path that I inserted is copy-paste, that is why I believe that is correct. I suppose that you are talking about the second code, and that I should insert "" quotes right? Furthermore, which solution is the best one? - Dimitra Micha

5 Answers

62
votes

I would use subprocess this way:

import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])

But, if you have a properly configured /proc/sys/fs/binfmt_misc/jar you should be able to run the jar directly, as you wrote.

So, which is exactly the error you are getting? Please post somewhere all the output you are getting from the failed execution.

13
votes

This always works for me:

from subprocess import *

def jarWrapper(*args):
    process = Popen(['java', '-jar']+list(args), stdout=PIPE, stderr=PIPE)
    ret = []
    while process.poll() is None:
        line = process.stdout.readline()
        if line != '' and line.endswith('\n'):
            ret.append(line[:-1])
    stdout, stderr = process.communicate()
    ret += stdout.split('\n')
    if stderr != '':
        ret += stderr.split('\n')
    ret.remove('')
    return ret

args = ['myJarFile.jar', 'arg1', 'arg2', 'argN'] # Any number of args to be passed to the jar file

result = jarWrapper(*args)

print result
3
votes

I used the following way to execute tika jar to extract the content of a word document. It worked and I got the output also. The command I'm trying to run is "java -jar tika-app-1.24.1.jar -t 42250_EN_Upload.docx"

from subprocess import PIPE, Popen
process = Popen(['java', '-jar', 'tika-app-1.24.1.jar', '-t', '42250_EN_Upload.docx'], stdout=PIPE, stderr=PIPE)
result = process.communicate()
print(result[0].decode('utf-8'))

Here I got result as tuple, hence "result[0]". Also the string was in binary format (b-string). To convert it into normal string we need to decode with 'utf-8'.

1
votes

With args: concrete example using Closure Compiler (https://developers.google.com/closure/) from python

import os
import re
src = test.js
os.execlp("java", 'blablabla', "-jar", './closure_compiler.jar', '--js', src, '--js_output_file',  '{}'.format(re.sub('.js$', '.comp.js', src)))

(also see here When using os.execlp, why `python` needs `python` as argv[0])

0
votes

How about using os.system() like:

os.system('java -jar blabla...')

os.system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.