gpt4 book ai didi

Java Runtime.getRuntime().exec 不同的输出格式

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:49 25 4
gpt4 key购买 nike

我有一个简单的Python程序(hw1.py)如下:

x = int(input("Enter x value: "))
y = int(input("Enter y value: "))

print("x is " + str(x))
print("y is " + str(y))
print("Output is " + str(x+y))

当我从终端运行它时,我按预期得到以下输出:

Enter x value: 10
Enter y value: 20
x is 10
y is 20
Output is 30

但是,当我从 Java 运行它并提供输入(“10”和“20”)时,我得到的输出略有不同。以下是编译和运行 python 文件的 Java 代码:

String osName = System.getProperty("os.name").toLowerCase();
boolean isMacOs = osName.startsWith("mac os x");
String macPythonPath = "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3";
String unixPythonPath = "/usr/bin/python3";
Process p;
if (isMacOs) {
p = Runtime.getRuntime().exec(macPythonPath + " -m py_compile " + "/Users/inanc/Desktop/pythonDocs/hw1.py");

} else {
p = Runtime.getRuntime().exec(unixPythonPath + " -m py_compile " + "/Users/inanc/Desktop/pythonDocs/hw31.py");
}

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


String resError = "", s;
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
resError = resError + s + "\n";
}
resError = resError.trim();
stdError.close();

if (resError.equals("")) {

if (isMacOs) {
p = Runtime.getRuntime().exec(macPythonPath + " " + "/Users/inanc/Desktop/pythonDocs/hw1.py");

} else {
p = Runtime.getRuntime().exec(unixPythonPath + " " + "/Users/inanc/Desktop/pythonDocs/hw1.py");
}
String[] inputs = {"10", "20"};
OutputStream out = p.getOutputStream();
for (String input: inputs) {
if (input.equals("") == false)
out.write((input+"\n").getBytes());
}
out.flush();

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

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

// read the output from the command
String res = "";
s = null;
while ((s = stdInput.readLine()) != null) {
res = res + s + "\n" ;
}
res = res.trim();

resError = "";
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
resError = resError + s + "\n";
}
resError = resError.trim();
stdInput.close();
stdError.close();
p = null;
System.out.println(res);
} else {
System.err.println(resError);
}

调用此代码后,输出如下:

Enter x value: Enter y value: x is 10
y is 20
Output is 30

如何通过终端执行获得完全相同的输出?至少我想在输入输入后保留换行符。

最佳答案

只有当你编写程序时,才有一种方法,将参数 10 写入进程,然后从进程中读取下一行,然后将 20 写入进程,然后从进程中读取另一行,依此类推

然而,在您的代码中,您在单个循环中编写流程所需的所有输入

关于Java Runtime.getRuntime().exec 不同的输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993563/

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