首页 > 解决方案 > 从 JAR 文件中执行 python 脚本

问题描述

我正在尝试编写一个执行 python 脚本的 Java 应用程序,以便将值返回给原始程序。但是,脚本是用 Python3 编写的,所以我不能使用 Jython。

我当前的程序在 Intellij 中运行良好,但是当我导出到 JAR 文件时它不再运行(我假设是因为文件路径不同)。我知道过去曾提出过类似的问题,但似乎没有一个解决方案有效。

String currentPath = new File("").getAbsolutePath();
String path = Paths.get(currentPath, "src", "com", "engine", "pythonScript.py").toUri().toString();

String[] cmd = new String[]{"python", path, data};
try {
    Process p = Runtime.getRuntime().exec(cmd);

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

    String output;

    while ((output = stdInput.readLine()) != null) {
        System.out.println(output);
        if (checkOutput(output)) {
            return output;
        }
    }

    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String s;
    while ((s=error.readLine()) != null) {
        System.out.println(s);
    }

} catch (IOException e) {
    e.printStackTrace();
}

标签: javapython

解决方案


推荐阅读