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

问题描述

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

python Main.py

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

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

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

这是我为了执行外部python代码调用的示例java代码

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

解决方法

java 进程在 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);
    }

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

,

如 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

Heres the ProcessBuilder docs for quick reference