0

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

import os.path
import 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', '-cp', 'model/classification', java_class]
    process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
    stdout, stderr = process.communicate(stdin)



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

My problem is, that in the main method of my java program String[]argsis empty. My input sequence of 5 5 5 5 5 5 5 does not reach the java program.

Calling java Model 5 5 5 5 5 5 5 from the console works as expected

Community
  • 1
  • 1
d4rty
  • 3,970
  • 5
  • 34
  • 73

1 Answers1

0

You are passing the args in on stdin, which you would need to read in Java using the appropriate methods.

Instead of that, you can just add the args to the end of your command array. This way they will be command line arguments that show up in your args[] array in Java. Note that it needs an array with an element for each arg, so I added a call to split.

def execute_java(java_file, args):
    java_class, ext = os.path.splitext(java_file)
    cmd = ['java', '-cp', 'model/classification', java_class] + args
    process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
    stdout, stderr = process.communicate()

execute_java('Model', '5 5 5 5 5 5 5'.split())
Ryan Widmaier
  • 7,948
  • 2
  • 30
  • 32