I'm trying to run a java class from a python script with subprocess.call():
import os
import subprocess
java_file = os.getcwd() + "/src/ch/idsia/scenarios/Main.java"
if os.path.isfile(java_file):
java_class, _ = os.path.splitext(java_file)
cmd = ['java', java_class]
subprocess.call(cmd, shell=False)
But running this python script gives me Error: Could not find or load main class .Users.alavin.Code.MarioAI_ver02_April_2011.src.ch.idsia.scenarios.Main. I've also tried the following variations for java_class:
"Users.alavin.Code.MarioAI_ver02_April_2011.src.ch.idsia.scenarios.Main"
"src.ch.idsia.scenarios.Main"
The python script is located in "Users/alavin/Code/MarioAI_ver02_April_2011/". The java class is "Main.java" in package "src.ch.idsia.scenarios". The java project is in Eclipse.
Notes: mac osx 10.9; python 2.7; java 1.7; using jython is not an option; running echo $CLASSPATH from the terminal gives a blank line.
Thank you in advance for any help/guidance.
2 Answers 2
Try using the -cp option to specify the class path, e.g.
java -cp /Users/alavin/Code/MarioAI_ver02_April_2011/src/ch/idsia/scenarios Main
So,
subprocess.call(['java', '-cp', '/Users/alavin/Code/MarioAI_ver02_April_2011/src/ch/idsia/scenarios', 'Main'])
Edit
Since Main is in package src.ch.idsia.scenarios try amending the command to:
subprocess.call(['java', '-cp', '/Users/alavin/Code/MarioAI_ver02_April_2011', 'src.ch.idsia.scenarios.Main'])
5 Comments
Error: Could not find or load main class Main.sys.path.append('/Users/alavin/Code/MarioAI_ver02_April_2011'), but still the same error.1 the expected output? If not then you need to figure out exactly how to run the Java program from the command line and then put that same command into your Python code.0 is the expected output. Could you please advise how I can run correctly from the command line? I think the issue is with either my CLASSPATH or python system path, or both.The classpath was the issue; I needed to include the jar files in the call from the terminal: java -cp bin/MarioAI/:lib/asm-all-3.3.jar:lib/jdom.jar ch.idsia.scenarios.Main. So running the subprocess command in python would be:
import subprocess
cmd = ['java', '-cp', 'bin/MarioAI/:lib/asm-all-3.3.jar:lib/jdom.jar', 'ch.idsia.scenarios.Main']
subprocess.call(cmd, shell=False)
To check the jar files in the classpath via Eclipse: right click Main.java -> Run Configurations -> Classpath tab.
Main.classis present in/Users/alavin/Code/MarioAI_ver02_April_2011/src/ch/idsia/scenarios/Main.classis in/Users/alavin/Code/MarioAI_ver02_April_2011/bin/ch/idsia/scenarios/. I.e. the.javafiles in the 'src/' directory have their corresponding.classfiles in thebin/directory. Is this a problem?