Java中如何调用Python

WBOY
WBOY 转载
2023-05-17 12:08:12 1466浏览

    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>

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

    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: jython
    Version: 2.7.2
    Language: python
    Short 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());
            }
        }
    }

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

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除