gpt4 book ai didi

java 模拟用户输入到外部程序

转载 作者:行者123 更新时间:2023-12-01 16:22:20 26 4
gpt4 key购买 nike

我需要使用Python程序来计算一些东西并得到结果。这个Python程序需要一个很长的输入,以至于我在调用该Python程序时无法将它作为参数传递。

我将简化这个问题。这是一个等待用户输入并打印用户输入的Python程序。我想用Java来完成输入并得到Python程序打印的内容。

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

我尝试使用BufferedWriterDataOutputStream来写入字符串,但两者似乎都不起作用。

这是我迄今为止尝试从 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,除此之外我还注意到 \nwriter.flush() 都是需要的。

最佳答案

你必须写一个换行符\n,否则Python的输入不会被读取。就像用户从未按下 Enter 键一样。

关于java 模拟用户输入到外部程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62234919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com