Reputation: 97
i am using jenkins in ubuntu and i need to call a java class from python script. The code:
import os
import shutil
import sys
from subprocess import call, STDOUT
param1=os.getenv(‘PARAM1’)
param2=os.getenv(‘PARAM2’)
param3=os.getenv(‘PARAM3’)
cmd1 =”cp /…/Class.class $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER/Class.class ”
cmd2=”java $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER/Class ” +””+param1+””+param2””+param3
print>>> sys.stder, “Launching command: “ + cmd2
call(cmd1,shell=True)
call(cmd2,shell=True)
But the console output shows “Error: Could not find or load main class” I have checked an the file was copied, and Jenkis have installed the Java SE Development Kit 8u31 version. I have try build the process in two step, first copy the java file and later set up the variables and do the second call but appears the same error. Thanks,
i have changed the code to:
classpath=os.path.join(os.getenv('JENKINS_HOME'),"jobs",os.getenv(JOB_NAME'),"builds",os.getenv('BUILD_NUMBER'))
cmd2=[“java”,”-classpath”,classpath,”Class”,param1,param2,param3]
call(cmd2)
The code Works!!!
When i build with parameters the console output shows "Usage_ java [- options] class [args...]..."
Upvotes: 2
Views: 12643
Reputation: 328840
Java doesn't support "run this file as a class" directly. Instead, you need to add the class to the classpath and then call it using the Java Fully Qualified name:
java -classpath $JENKINS_HOME/jobs/$JOB_NAME/builds/$BUILD_NUMBER com.foo.Class ...
would run the Java code in .../builds/$BUILD_NUMBER/com/foo/Class.class
Note: Avoid call()
with a string. Instead build a list of command plus arguments. That way, you can replace variables correctly and spaces in file names won't cause unexpected/hard to find problems:
classpath = os.path.join(os.genenv("JENKINS_HOME), "jobs", ...)
cmd = [
"java",
"-classpath",
classpath,
"Class",
...
]
call(cmd)
Upvotes: 1