Spring Boot调用Python脚本

1、准备工作

在D盘创建一个python脚本,脚本路径为D:\python\hello.py,脚本内容为
print(“Hello World!”)
在代码中定义python脚本
private static final String PATH = “D:\python\helloWorld.py”;

2、Spring Boot调用Python脚本的方法

方法一:使用ProcessBuilder

  ProcessBuilder类是J2SE 1.5在java.lang中新添加的一个新类,此类用于创建操作系统进程,它提供一种启动和管理进程(也就是应用程序)的方法。在J2SE 1.5之前,都是由Process类处理实现进程的控制管理。每个 ProcessBuilder 实例管理一个进程属性集。它的start() 方法利用这些属性创建一个新的 Process 实例。start() 方法可以从同一实例重复调用,以利用相同的或相关的属性创建新的子进程

 @Test
    public void testMethod1() throws IOException, InterruptedException
    {
        final ProcessBuilder processBuilder = new ProcessBuilder("python", PATH);
        processBuilder.redirectErrorStream(true);
        final Process process = processBuilder.start();
        final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s = null;
        while ((s = in.readLine()) != null)
        {
            System.out.println(s);
        }

        final int exitCode = process.waitFor();
        System.out.println(exitCode == 0);
    }
方法二:使用executor

  Executor框架用于执行异步任务,单个的线程既是工作单元也是执行机制,从JDK1.5开始,为了把工作单元与执行机制分离开,Executor框架诞生了,他是一个用于统一创建与运行的接口。Executor框架实现的就是线程池的功能。

pom依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>
@Test
    public void testMethod2(){
        final String line = "python " + PATH;
        final CommandLine cmdLine = CommandLine.parse(line);
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream())
        {
            final PumpStreamHandler streamHandler = new PumpStreamHandler(baos);
            final DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(streamHandler);
            final int exitCode = executor.execute(cmdLine);

            log.info("调用Python脚本的执行结果: {}.", exitCode == 0 ? "成功" : "失败");
            log.info(baos.toString().trim());
        }
        catch (final IOException e)
        {
            log.error("调用Python脚本出错", e);
        }
    }

完整代码如下,添加对应的依赖即可:

package cn.itcast;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test1 {
    private static final String PATH = "D:\\python\\helloWorld.py";
    private static Logger log = LoggerFactory.getLogger(Test1.class);
    @Test
    public void testMethod1() throws IOException, InterruptedException
    {
        final ProcessBuilder processBuilder = new ProcessBuilder("python", PATH);
        processBuilder.redirectErrorStream(true);
        final Process process = processBuilder.start();
        final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s = null;
        while ((s = in.readLine()) != null)
        {
            System.out.println(s);
        }

        final int exitCode = process.waitFor();
        System.out.println(exitCode == 0);
    }

    @Test
    public void testMethod2(){
        final String line = "python " + PATH;
        final CommandLine cmdLine = CommandLine.parse(line);
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream())
        {
            final PumpStreamHandler streamHandler = new PumpStreamHandler(baos);
            final DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(streamHandler);
            final int exitCode = executor.execute(cmdLine);

            log.info("调用Python脚本的执行结果: {}.", exitCode == 0 ? "成功" : "失败");
            log.info(baos.toString().trim());
        }
        catch (final IOException e)
        {
            log.error("调用Python脚本出错", e);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值