用java函数执行python脚本

2024-10-03 15:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在java函数中执行python脚本。我试过一些东西,但效果不好

这是我的代码:

private static void generateReport() {
    try {
        Runtime.getRuntime().exec("python ReportGeneration/reportGeneration.py");
    } catch (IOException e) {
        log.error(e);
    }

}

这是我的运行.sh文件:

^{pr2}$

当我尝试单独运行python脚本时(使用python报表生成.py命令行中的命令)它给我一个输出,但当我尝试用java函数执行它时,它没有给出任何输出?我的代码有错误吗?在

提前谢谢


Tags: 函数代码py脚本staticjavaprivateruntime
1条回答
网友
1楼 · 发布于 2024-10-03 15:25:27

您可以使用Jython library在java代码中运行python脚本。在

例如:

import org.python.util.PythonInterpreter;

import java.util.Properties;

public class Main {

public static void main(String[] args) {
    initializeJython();
    PythonInterpreter interpreter = new PythonInterpreter();

    interpreter.exec("print \"Hello World\"");
    //interpreter.execfile(); // You can also execute script from a file.
}

private static void initializeJython() {
    Properties props = new Properties();
    props.put("python.console.encoding", "UTF-8");
    props.put("python.import.site", "false"); //Jython doesn't work for me without setting this property to false.

    PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
}

}

如果您的项目是基于maven的,您可以像这样添加jython依赖项:

^{pr2}$

相关问题 更多 >