开发者

Java中调用Python的实现示例

目录
  • Java core
    • 使用ProcessBuilder
    • 使用Java脚本引擎
  • 总结

    python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用。DataX 是阿里开源的一个异构数据源离线同步工具,致力于实现包括关系型数据库(mysql、oracle等)、HDFS、Hive、ODPS、HBase、FTP等各种异构数据源之间稳定高效的数据同步功能。Datax也是通过Java调用Python脚本。本文介绍几种方法从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),为了使得当执行脚本出现错误时,错误输www.devze.com出流被合并至标准输出流。这样设置可以从Process对象的getInputStream()方法中读取错误信息。如果没有该设置,则需要分别用两个方法获取流:getInputStream() 和 getErrorStream() 。processBuilder.start()获取Process对象,然后读取输出流并验证结果。

    使用Java脚本引擎

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

    <dependency>
        <groupId>org.python</groupId>
        <artifactId>jython</artifactId>
        <version>2.7.2</version>
    </dependency>

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

    public static void listEngines() {
      Script编程EngineManager 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: jython

    Version: 2.7.2

    Language: python

    Shopythonrt Names:

    python

    jython

    现在使用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());
        }
      }
    }

    总结

    本文介绍了如何从Jpythonava调用Python脚本,使用jython脚本引擎比ProcessBuilder类更简单。另外Python可以便捷搭建http应用,Java也可以通过HTTP协议直接调用HTTP服务实现交互。

    参考内容:https://www.baeldung.com/java-working-with-python

    到此这篇关于Java中调用Python的实现示例的文章就介绍到这了,更多相关Java调用Python内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜