java simulate user input to external program

回眸只為那壹抹淺笑 提交于 2020-06-17 15:51:02

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/62234919/java-simulate-user-input-to-external-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!