I'm wanting to write testing scripts for Java classes using Python. I am able to compile, run, provide input, and capture output using subprocess
, java.util.Scanner
, and other tools. The code runs, but I'm not capturing the run log I was hoping to.
The Issue
As of now the output is captured without including the input... I'm getting (where 1, 2, 3, 4 is the input from a file):
Number? Number? Number? Number? Sum: 10
I want to capture:
Number? 1
Number? 2
Number? 3
Number? 4
Sum: 10
Current Code
Python
import os.path, subprocess
def compile_java(java_file, inputFile):
#setup input file
stdin = get_expected(inputFile)
#compile java
subprocess.check_call(['javac', java_file])
#prep for running
java_class, ext = os.path.splitext(java_file)
cmd = ['java', java_class]
#run java with input, and capturing output
proc = subprocess.run(cmd, input=stdin, check=True, capture_output=True, text=True)
print(proc.stdout)
def get_expected(filename):
content = ""
with open(f'{filename}', 'r') as f:
for line in f.readlines():
content += line
return content
compile_java('Example.java', 'example.in')
Java - Example.java
import java.util.*;
public class Example{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0;
for(int i =0; i < 4; i++){
System.out.print("Number? ");
sum = sum + scan.nextInt();
}
System.out.println("Sum: " + sum);
}
}
Input File - example.in
1
2
3
4
Note: I'm wanting to test the Java file, so I don't want to edit the Java in any way. I'm hoping there is a way I can capture the output in this format through just changing the Python code.