Excute java class from python with extrnal jar and multiple args

Mostafa Mohamed :

I'm trying to build script to execute java class with passing data sample and getting the result from java. The java code uses external jar which already in the same path of my python file and java file

my script in python :

import os.path,subprocess
from subprocess import STDOUT,PIPE

def compile_java(java_file):
    subprocess.check_call(['javac', '-cp', 'commons-codec-1.7.jar', java_file])

def execute_java(java_file,args):
    java_class,ext = os.path.splitext(java_file)
    cmd = ['java', '-cp', 'commons-codec-1.7.jar', java_class]
    proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    stdout,stderr = proc.communicate(args)
    print(stdout)
compile_java('jf.java')
execute_java('jf.java',[1,2])

my java class sample:

import org.apache.commons.codec.binary.Base64;
public class jf {

    public static void main(String[] args) {

        System.out.println(args[0]);

    }
}

but i got errors while compling :

b'Error: Could not find or load main class jf\n'

I think the problem is with passing args to the main function, and how could i return value from java while main function is void function?

Paul Bombarde :

You specify a classpath to java through the -cp parameter. Java will look for the jf class in the given files and won't find it :

> java -cp commons-codec-1.7.jar jf toot
Error: Could not find or load main class jf

You don't really need commons-codec here. You may directly use the class name :

> java jf toot
toot

Or add . to your classpath if your real code needs additionnal jars :

> java -cp commons-codec-1.7.jar;. jf toot
toot

In your python :

cmd = ['java', '-cp', 'commons-codec-1.7.jar;.', java_class]

One additionnal point : as you need to pass arguments, I would not use proc.communicate as it send the data on the standard input (you need to use something like scanner in the java side), but simply append args to you cmd array:

cmd = ['java', '-cp', 'commons-codec-1.7.jar;.', java_class] + args

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148947&siteId=1