我需要使用Python程序来计算某些东西并获得结果。该Python程序需要很长的输入,以至于在调用该Python程序时无法将其作为参数传递。
我将简化这个问题。这是一个等待用户输入并打印用户输入的Python程序。我想使用Java完成输入并获取Python程序打印的内容。
print("Waiting for user input")
result = input()
print(result)
我尝试使用
BufferedWriter
和DataOutputStream
编写字符串,但是两者似乎都无法正常工作。这是到目前为止我尝试从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);
}
---------回答------
感谢Jurn Ho,除此之外,我还注意到同时需要
\n
和writer.flush()
。 最佳答案
您必须编写换行符\n
,否则不会读取python的输入。就像用户从不按Enter键一样。