在java中执行进程以调用外部python程序,但该程序不会将任何内容打印到控制台



我们可以使用Jython在java中实现python,但我不想采用那种方法,我想要的是使用命令行实用程序和fire python命令来执行代码并获得java代码中的控制台输出。

python Main.py<input.txt

我在终端中使用了上面的命令,它在那里工作,给我输出,但无法在java代码中获得输出。

注意:Main.py和input.txt以及java代码在同一文件夹中

我在java代码中做错了什么?

下面是我调用的示例java代码,以便执行外部python代码

try {
Process process = Runtime.getRuntime()
.exec("python Main.py < input.txt");

process.waitFor();
System.out.println(process);
StringBuilder output
= new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "n");
}
System.out.println("here");
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
} else {
System.out.println("Process failed");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}

下面是一个示例python代码:

x = input();
y = input();
print(type(x));
print(type(y));
print(x + y);

这是一个示例输入文件,我将其作为输入传递给python代码

30
40

正如sandip所示,在java中执行命令与通过BASH运行命令不同。起初我试图执行bash -c "python Main.py < input.txt"(通过java(。出于某种原因,这没有起作用,即使它起作用,它也不是一个好的解决方案,因为它依赖于它运行的系统。我发现有效的解决方案是使用ProcessBuilder首先生成命令,并将其输入重定向到文件。这允许您保持python代码不变,至少对我来说,可以得到与运行BASH命令相同的结果。示例:

ProcessBuilder pb = new ProcessBuilder("python3","Main.py");
//Make sure to split up the command and the arguments, this includes options
//I only have python3 on my system, but that shouldn't affect anything
pb.redirectInput(new File("./input.txt"));
System.out.println(pb.command());
Process process = pb.start();
//The rest is the exact same as the code in the question

以下是用于快速参考的ProcessBuilder文档

java进程不接受<在python命令中输入文件的符号。相反,你可以这样跑python文件

f = open("input.txt", "r")
for x in f:
print(type(x));
print(x)

java文件

Process process = Runtime.getRuntime().exec("python Main.py  input.txt");
process.waitFor();
System.out.println(process);
StringBuilder output
= new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "n");
}
System.out.println("here");
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
} else {
System.out.println("Process failed");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}

并使用相同的文本文件。它应该在控制台中打印

相关内容

最新更新