0

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.

6
  • 1
    Try using check_output instead of call and post the result. Commented May 29, 2016 at 17:38
  • I'm assuming you have looked at stackoverflow.com/questions/7372592/… and the three other questions it links to. Commented May 29, 2016 at 17:46
  • @TadhgMcDonald-Jensen Yes, I did and I tried all of the solutions but to no avail. Apoligies if it seems like a duplicated but I edited it to include the error. Commented May 29, 2016 at 17:57
  • @domoarrigato As you said, I have posted the error message, though I cant seem to decipher what is the problem. Commented May 29, 2016 at 18:00
  • what if you try with shell=True? Commented May 29, 2016 at 18:02

1 Answer 1

2

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

It also may be possible to use /usr/bin/env command which searches the PATH environment variable for the correct executable, so this also may work:

import subprocess
subprocess.call(['/usr/bin/env', 'java', '-jar', 'StatsCalc.jar'])

This is pretty consistently defined on unix systems but probably won't work well on windows.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.