RedCardOP RedCardOP - 6 months ago 92
Python Question

Attempting to execute .jar file using python

I have a .jar file that I need to execute via Python.

My current code is

import subprocess
subprocess.check_output(['java', '-jar', 'StatsCalc.jar'])


I printed out the error message:

Traceback (most recent call last):
File "C:\Users\ali\Documents\Java Stuff\RedditFitnessCalc\out\artifacts\RedditFitnessCalc_jar\pythonBotScript.py", line 6, in <module>
p = subprocess.check_output(['java', '-jar', 'RedditFitnessCalc.jar'])
File "C:\Program Files (x86)\Python 3\lib\subprocess.py", line 620, in check_output
raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command '['java', '-jar', 'RedditFitnessCalc.jar']' returned non-zero exit status 2


When I run it, a window pops up and disappears instantly. It is a java program that has a GUI. I tried running it directly and with a batch file and both work fine.

Answer

One thing that frequently works is using shell=True option on the subprocess, this executes the command as if it was done in a shell (batch file or command prompt)

So using:

import subprocess
subprocess.call(['java', '-jar', 'StatsCalc.jar'],shell=True)

Should work for you, but please read the Security Considerations section of the subprocess's documentation before relying too heavily on this.

Usually the reason it does not work without shell is because it cannot find the command java without using the full path, so if you know the full path of the java executable that would be preferable to using shell=True

import subprocess
subprocess.call(['path/to/java', '-jar', 'StatsCalc.jar'])

I don't know the exact details on the difference between these two but