0

I need to use a Python program to calculate something and get the result. This Python program need a so long input that I cann't pass it as parameter when calling that Python program.

I'm going to simplify this question. Here is a Python program waiting for user input and print the user input. I want to use Java to finish the inputting and get what Python program prints.

print("Waiting for user input")
result = input()
print(result)

I tried to use BufferedWriter and DataOutputStream to write the string, but both seem not to work.

Here is the code I tried so far learning from Java Process with Input/Output Stream:.

public void callExe() throws IOException {
    Process process = new ProcessBuilder("python", "C:/input.py").start();

//  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    DataOutputStream writer2 = new DataOutputStream(process.getOutputStream());
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

//  writer.write("5555555");
    writer2.writeBytes("5555");
    writer2.flush();

    // Read the output from the command:
    String s = null;
    while ((s = stdInput.readLine()) != null)
        System.out.println(s);

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
        System.out.println(s);
}

--------- Answer ------

Thanks to Jurn Ho, beyond that I also noticed that \n and writer.flush() are both needed.

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52

1 Answers1

0

You have to write a newline \n otherwise the input to python is not read. It's like the user never presses enter.

Jurn Ho
  • 69
  • 1
  • 5