49

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? Commented Sep 10, 2011 at 15:09
  • 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. Commented Sep 10, 2011 at 15:12
  • I have tried both of them in different ways, using the absolute paths, but always the same mistake. I am using macos Commented Sep 10, 2011 at 15:16
  • There are no quotes around java -jar Blender. Is that just a copy-and-paste error? Commented Sep 10, 2011 at 15:17
  • 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? Commented Sep 10, 2011 at 15:21

5 Answers 5

70

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.

Sign up to request clarification or add additional context in comments.

12 Comments

The only thing that IDLE says is invalid syntax. I don't really understand the term properly configured. Should I place it somewhere else. I just copied from my workspace to the folder where my python script is.
..and did it say just "syntax error" or there is some error trace too?
I think I found the mistake for the invalid syntax:) Thanks:)
you mean, environment variable? subprocess.call( ... , env={'JAVA_OPTS':' ... '})
to include arguments when executing a .jar file with subprocess.call(), simply append them to the end of the method separated by commas example: subprocess.call(['java', '-jar', 'Blender.jar', 'arg1', 'arg2', 'however_many_args_you_need'])
|
16

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

4 Comments

this gives the result of the jar program?
@bbeaudoin : I got this error (I am using python 3.6.0) -- TypeError: endswith first arg must be bytes or a tuple of bytes, not str for the line if line != '' and line.endswith('\n'):
So should I just create a new python script and save it in the save folder with my java code and run this script?
how can I find 'myJarFile.jar' this file? I didn't find any file with '.jar' except those in my libraries.
5

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

Comments

2

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.