Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I execute a jar file through a python script

Tags:

java

python

jar

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?

like image 471
Dimitra Micha Avatar asked Sep 10 '11 15:09

Dimitra Micha


People also ask

Can we call java jar from python?

Using Subprocess module – I found the subprocess as the best way to call any jar from python. Basically, If I say, It is one of the best ways to call any other cross-language package.

Can we execute JAR file?

To run JAR files, first make sure you have Java installed, your environment is properly configured, and the JAR file's manifest file lists the application's entry-point. With all of these puzzle pieces in place, your Java JAR file will run without issues.


2 Answers

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.

like image 158
redShadow Avatar answered Sep 21 '22 12:09

redShadow


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 
like image 35
bbeaudoin Avatar answered Sep 20 '22 12:09

bbeaudoin