48

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?

Community
  • 1
  • 1
Dimitra Micha
  • 2,089
  • 8
  • 27
  • 31
  • What errors are you getting? Is the `PATH` env var set correctly? – NullUserException Sep 10 '11 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. – Dimitra Micha Sep 10 '11 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 – Dimitra Micha Sep 10 '11 at 15:16
  • There are no quotes around `java -jar Blender`. Is that just a copy-and-paste error? – NullUserException Sep 10 '11 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? – Dimitra Micha Sep 10 '11 at 15:21

5 Answers5

69

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.

redShadow
  • 6,687
  • 2
  • 31
  • 34
  • 1
    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. – Dimitra Micha Sep 10 '11 at 15:33
  • ..and did it say just "syntax error" or there is some error trace too? – redShadow Sep 10 '11 at 15:38
  • I think I found the mistake for the invalid syntax:) Thanks:) – Dimitra Micha Sep 10 '11 at 15:40
  • Just one more question, in the call method I should include the path for the Blender.jar right? – Dimitra Micha Sep 10 '11 at 15:43
  • It is good practice to always refer to files using their full absolute path. If it resides in the same directory of your script, I recommend you use `os.path.abspath(os.path.join(os.path.dirname(__file__), 'Blender.jar'))`. Did you manage to get your jar running, btw? – redShadow Sep 10 '11 at 16:02
  • I will try to use that:) Thanks. I think the problem is that I should include some VM arguments that are not included in my jar (Eclipse suggested that I should include them while I execute the jar). Do you have any idea how I can do that? – Dimitra Micha Sep 10 '11 at 16:11
  • is there a way to specify JAVA_OPTS in this subprocess call? – user1164061 Feb 07 '13 at 22:09
  • 1
    you mean, environment variable? ``subprocess.call( ... , env={'JAVA_OPTS':' ... '})`` – redShadow Feb 08 '13 at 11:59
  • 10
    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'])` – scottysseus Aug 02 '13 at 21:54
  • I get `{TypeError}bufsize must be an integer` when i structure my `subprocess.call` like this. If i simply write out the command as `java -jar file.jar arg1 ` I get `Error: Unable to access jarfile` error. – partydog Dec 12 '17 at 22:05
  • For windows if you have the jar in different path then use `subprocess.call(['java', '-jar', 'C:\\utils\\my_java.jar'])` – hru_d Apr 22 '20 at 06:47
  • @redShadow: When I am trying to execute a jar within Intellij IDE in a python project:: subprocess.call(['java', '-jar', 'C:\\Dev\\qa-automation\\CLIP\\hive-jdbc.jar' ]) Then Getting Error >>> no main manifest attribute, in C:\Dev\qa-automation\CLIP\hive-jdbc.jar I attached jar in module setting but project is not recognizing it. Pls suggest. – Rohit Jun 24 '20 at 19:31
15

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
bbeaudoin
  • 149
  • 1
  • 3
  • this gives the result of the jar program? – TanMath Sep 13 '15 at 18:47
  • 3
    @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'): – Bikash Gyawali Jul 12 '17 at 09:58
  • So should I just create a new python script and save it in the save folder with my java code and run this script? – Cecilia Nov 06 '19 at 15:48
  • how can I find 'myJarFile.jar' this file? I didn't find any file with '.jar' except those in my libraries. – Cecilia Nov 06 '19 at 15:52
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'.

Harsha Reddy
  • 391
  • 5
  • 8
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])

Community
  • 1
  • 1
Wajih
  • 905
  • 9
  • 13
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.

NilVS
  • 181
  • 1
  • 2
  • 9