I have written python code to invoke .java file, compile it & execute it using python. I'm using following python code
import os
import os.path,subprocess
from subprocess import STDOUT,PIPE
path='Location where my .java file is'
os.chdir(path)
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
compile_java('Hello.java')
execute_java("Hello")
My .java file contains simple hello world code. The code is given below
public class Hello {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
My python code is running successfully but I'm not getting "Hello World" message in my python console. Can you please help me to print java output(Hello World) in my python console? Thanks in advance
asked May 3, 2017 at 17:22
Python Learner
4473 gold badges13 silver badges30 bronze badges
1 Answer 1
You can execute the command using popen:
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = 'java '+ java_class
f = os.popen(cmd)
print f.read()
answered May 3, 2017 at 17:32
Bajal
6,1563 gold badges23 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Python Learner
Thank you @Bajal.It's working now for single println. But if I want to retrieve if I want to retrieve multiple output using while loop then it is not working. For example it is not working for while (result.next()) { //Retrieve by name String name = result.getString(1); //Retrieve by address String address = result.getString(2); //Retrieve by company String company = result.getString(3); System.out.println(name+":"+family+":"+company); } Can you please suggest
Bajal
Actually the same code should work for multiple lines output because it just prints out the entire STDOUT. Is it possible that your resultSet only has one row, by any chance?
default
cmdusing subprocess.