首页 > Java > java教程 > 正文

Java中如何调用Python

WBOY
发布: 2023-05-17 12:08:12
转载
2502人浏览过

    python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用python代码的需求很常见、实用。datax 是阿里开源的一个异构数据源离线同步工具,致力于实现包括关系型数据库(mysql、oracle等)、hdfs、hive、odps、hbase、ftp等各种异构数据源之间稳定高效的数据同步功能。datax也是通过java调用python脚本。

    Java core

    Java提供了有两种方法,分别为ProcessBuilder API和 JSR-223 Scripting Engine。

    使用ProcessBuilder

    通过ProcessBuilder创建本地操作系统进程启动python并执行Python脚本, hello.py脚本简单输出“Hello Python!”。需要开发环境已经安装了python,并设置了环境变量。

    @Test
    public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py"));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        List<String> results = readProcessOutput(process.getInputStream());
        assertThat("Results should not be empty", results, is(not(empty())));
        assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Python!")));
        int exitCode = process.waitFor();
        assertEquals("No errors should be detected", 0, exitCode);
    }
    private List<String> readProcessOutput(InputStream inputStream) throws IOException {
        try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
            return output.lines()
                .collect(Collectors.toList());
        }
    }
    private String resolvePythonScriptPath(String filename) {
        File file = new File("src/test/resources/" + filename);
        return file.getAbsolutePath();
    }
    登录后复制

    要重写这句话可这样说: 使用带有一个参数的Python命令来启动,该参数是Python脚本的完整路径。可以放在java工程的resources目录下。需要注意的是:redirectErrorStream(true),为了使得当执行脚本出现错误时,错误输出流被合并至标准输出流。可以通过调用Process对象的getInputStream()方法来读取错误信息。如果没有该设置,则需要分别用两个方法获取流:getInputStream() 和 getErrorStream() 。从ProcessBuilder中获取Process对象后,通过读取输出流来验证结果。

    使用Java脚本引擎

    JSR-223规范是Java 6首次引入的,该规范定义了一组脚本API,可以提供基本脚本功能。这些API提供了在Java和脚本语言之间共享值及执行脚本的机制。该规范主要目的是为了统一Java与不同实现JVM的动态脚本语言的交互,Jython是在jvm上运行python的java实现。假设我们在CLASSPATH上有Jython,框架自动发现我们有可能使用该脚本引擎,并允许我们直接请求Python脚本引擎。在Maven中,我们可以引用Jython,也可以直接下载安装它

    <dependency>
        <groupId>org.python</groupId>
        <artifactId>jython</artifactId>
        <version>2.7.2</version>
    </dependency>
    登录后复制

    可以通过下面代码列出所有支持的脚本引擎:

    立即学习Java免费学习笔记(深入)”;

    public static void listEngines() {
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> engines = manager.getEngineFactories();
        for (ScriptEngineFactory engine : engines) {
            LOGGER.info("Engine name: {}", engine.getEngineName());
            LOGGER.info("Version: {}", engine.getEngineVersion());
            LOGGER.info("Language: {}", engine.getLanguageName());
            LOGGER.info("Short Names:");
            for (String names : engine.getNames()) {
                LOGGER.info(names);
            }
        }
    }
    登录后复制

    如果Jython在环境中可用,应该看到相应的输出:

    ...Engine name: jythonVersion: 2.7.2Language: pythonShort Names:pythonjython

    现在使用Jython调用hello.py脚本:

    @Test
    public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception {
        StringWriter writer = new StringWriter();
        ScriptContext context = new SimpleScriptContext();
        context.setWriter(writer);
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("python");
        engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context);
        assertEquals("Should contain script output: ", "Hello Python!", writer.toString().trim());
    }
    登录后复制

    使用该API比上面的示例更简洁。在设置ScriptContext时,需要将StringWriter包含其中,以便保存脚本执行的输出。然后提供简称让ScriptEngineManager 查找脚本引擎,可以使用python或jython。最后验证输出是否与期望一致。

    其实也可以使用PythonInterpretor 类直接调用嵌入的python代码:

    @Test
    public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            StringWriter output = new StringWriter();
            pyInterp.setOut(output);
            pyInterp.exec("print('Hello Python!')");
            assertEquals("Should contain script output: ", "Hello Python!", output.toString().trim());
        }
    }
    登录后复制

    PythonInterpreter类提供的exec方法可直接执行Python代码。和前面示例一样通过StringWriter 捕获执行输出。下面再看一个示例:

    @Test
    public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            pyInterp.exec("x = 10+10");
            PyObject x = pyInterp.get("x");
            assertEquals("x: ", 20, x.asInt());
        }
    }
    登录后复制

    上面示例可以使用get方法访问变量值。下面示例看如何捕获错误:

    try (PythonInterpreter pyInterp = new PythonInterpreter()) {
        pyInterp.exec("import syds");
    }
    登录后复制

    运行上面代码会抛出PyException 异常,与在本地执行Python脚本输出错误一样。

    下面有几点注意事项:

    • PythonIntepreter 实现了AutoCloseable,最好与 try-with-resources 一起使用。

    • PythonIntepreter类名不是表示Python代码的解析器,Python程序在Jython是运行在jvm中,执行前需要编译为java字节码。

    • 尽管Jython是Java的Python实现,但它可能不包含与本机Python相同的所有子包。

    下面示例展示如何把java变量赋给Python变量:

    import org.python.util.PythonInterpreter; 
    import org.python.core.*; 
    class test3{
        public static void main(String a[]){
            int number1 = 10;
            int number2 = 32;
            try (PythonInterpreter pyInterp = new PythonInterpreter()) {
                python.set("number1", new PyInteger(number1));
                python.set("number2", new PyInteger(number2));
                python.exec("number3 = number1+number2");
                PyObject number3 = python.get("number3");
                System.out.println("val : "+number3.toString());
            }
        }
    }
    登录后复制

    以上就是Java中如何调用Python的详细内容,更多请关注php中文网其它相关文章!

    python速学教程(入门到精通)
    python速学教程(入门到精通)

    python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

    下载
    来源:亿速云网
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
    最新问题
    开源免费商场系统广告
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送
    PHP中文网APP
    随时随地碎片化学习
    PHP中文网抖音号
    发现有趣的

    Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号