0

I followed the SO Answer to execute a java program from python

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


def compile_java(java_file):
    subprocess.check_call(['javac', java_file])


def execute_java(java_file, stdin):
    java_class, ext = os.path.splitext(java_file)
    cmd = ['java', java_class]
    process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
    stdout, stderr = process.communicate(stdin)
    print(stdout)


compile_java(os.path.join('model', 'classification', 'Model.java'))
execute_java('Model', '5 6 7 8')

The python code compiles the /model/classification/Model.java without problems. But when the python code executes the java program, Java can not find or load the main class Model. Executing java Model in the command line in the same directory (with the compiled version, which was triggered by the python snippet above) works.

d4rty
  • 3,970
  • 5
  • 34
  • 73

1 Answers1

0

The problem seems to be, that you have to add the directory of your *.class file to the classpath! You compiled the class in the directory model/classification so the path of your *.class file is model/classification/Model.class. For executing this bytecode you need to add the directory to classpath by writing java -cp model/classification Model...

This python code works for me:

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

def compile_java(java_file):
    subprocess.check_call(['javac', java_file])

def execute_java(java_file, stdin):
    java_class,ext = os.path.splitext(java_file)

    // I changed the following line by adding the directory to the classpath
    cmd = ['java', '-cp', 'model/classification', java_class]

    proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    stdout,stderr = proc.communicate(stdin)
    print ('This was "' + stdout + '"')

compile_java(os.path.join('model', 'classification', 'Model.java'))
execute_java('Model.java', '5 6 7 8')

In this case, the directory path is relative to the execution directory of your python script!

0x1C1B
  • 1,204
  • 11
  • 40
  • I'd sooner guess the problem is that the class is `model.classification.Model` (so `Model` in the package `model.classification`), and not `Model` (or `Model.java` as your code tries) in the `model/classification` folder. – Mark Rotteveel May 23 '18 at 18:53
  • @MarkRotteveel Okay yea that would be also one possible source for this problem... – 0x1C1B May 23 '18 at 18:55
  • @MarkRotteveel But he compiled the class in a sub-directory without adding the directory to classpath so I assumed that the problem is the missing directory and not any package problem... – 0x1C1B May 23 '18 at 18:58
  • No, javac can compile (assuming it doesn't reference other files in that package), but java can't execute that way. – Mark Rotteveel May 23 '18 at 19:02