SoFunction
Updated on 2025-04-05

Example of implementation of springboot calling python script

In modern software development, sometimes we need to call external scripts, such as Python scripts, in Java applications. Spring Boot provides flexible ways to integrate these external scripts. This article will introduce in detail how to call Python scripts in Spring Boot applications, including two different methods: Java'sProcessBuilderClasses and use the Apache Commons Exec library.

Preparation

Before we start, we need to prepare a Python script. Please follow these steps:

  • Create a name called on disk Dpythonfolder.
  • Create a folder calledThe Python script, the content is as follows:
print("Hello World!!")
  • Define the path to a Python script in a Spring Boot project:
private static final String PATH = "D:\\python\\";

Method 1: Use ProcessBuilder

ProcessBuilderis a class provided by Java that allows us to start and manage operating system processes. The following is usedProcessBuilderSteps to call Python scripts:

1. Write test methods

In a Spring Boot application, we can write a test method to call a Python script:

@Test
public void testMethod1() throws IOException, InterruptedException {
    final ProcessBuilder processBuilder = new ProcessBuilder("python", PATH);
    (true);

    final Process process = ();

    final BufferedReader in = new BufferedReader(new InputStreamReader(()));

    String s = null;
    while ((s = ()) != null) {
        (s);
    }

    final int exitCode = ();
    (exitCode == 0);
}

2. Explain the code

  • ProcessBuilderThe constructor accepts the commands and parameters to be executed. Here, we passed"python"and script pathPATH
  • redirectErrorStream(true)Merge the error stream and the standard stream so that we can read the output from the same stream.
  • ()Start the process.
  • useBufferedReaderRead the output of the process.
  • ()Wait for the process to end and return the exit code.

Method 2: Use Apache Commons Exec

Apache Commons Exec provides a more advanced API to execute external processes. First of all, we need toAdd dependencies to the file:

<dependency>
    <groupId></groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>

1. Write test methods

The code for calling Python scripts using Apache Commons Exec is as follows:

@Test
public void testMethod2() {
    final String line = "python " + PATH;
    final CommandLine cmdLine = (line);

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        final PumpStreamHandler streamHandler = new PumpStreamHandler(baos);

        final DefaultExecutor executor = new DefaultExecutor();
        (streamHandler);

        final int exitCode = (cmdLine);

        ("CallPythonThe execution result of the script: {}.", exitCode == 0 ? "success" : "fail");
        (().trim());
    } catch (final IOException e) {
        ("Error calling Python script", e);
    }
}

2. Explain the code

  • (line)Analysis of the command to be executed.
  • PumpStreamHandlerRedirect the output stream toByteArrayOutputStream
  • DefaultExecutorUsed to execute commands.
  • (cmdLine)Execute the command and return the exit code.
  • andUsed to record execution results and errors.

The data of Python scripts is received through the interface by Spring Boot

Python scripts as services

In order to enable Spring Boot to receive data from Python scripts, we can wrap the Python scripts into an HTTP service. In this way, Spring Boot can call Python scripts through HTTP requests and receive the data it returns. Here are the steps to achieve this:

1. Create a Python HTTP service using Flask

First, we need to add the Flask library to our Python scripts to create a simple HTTP service. The following is the modified

from flask import Flask, jsonify
app = Flask(__name__)

@('/hello', methods=['GET'])
def hello_world():
    return jsonify(message="Hello World!!")

if __name__ == '__main__':
    (host='0.0.0.0', port=5000)

This code creates a Flask application, which is in5000Run on the port and define a/helloRoute, return a JSON response.

2. Call Python HTTP service in Spring Boot

Now, we need to call this Python HTTP service in our Spring Boot application. We can useRestTemplateorWebClientTo send an HTTP request.

Use RestTemplate

In Spring Boot, you can addRestTemplateDependencies:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Then, create a service to invoke the Python service:

import ;
import ;

@Service
public class PythonService {
    private static final String PYTHON_SERVICE_URL = "http://localhost:5000/hello";

    public String callPythonService() {
        RestTemplate restTemplate = new RestTemplate();
        String result = (PYTHON_SERVICE_URL, );
        return result;
    }
}

Using WebClient

If you are using Spring WebFlux, you can useWebClient

import ;
import ;

@Service
public class PythonService {
    private static final String PYTHON_SERVICE_URL = "http://localhost:5000/hello";
    private final WebClient webClient;

    public PythonService( webClientBuilder) {
         = (PYTHON_SERVICE_URL).build();
    }

    public String callPythonService() {
        return ()
                .retrieve()
                .bodyToMono()
                .block();
    }
}

in conclusion

By wrapping Python scripts into HTTP services, we can more easily call Python scripts in Spring Boot applications and receive the data it returns. This approach is not only suitable for Python scripts, but also for any external service that can provide an HTTP interface. In this way, Spring Boot applications can interact with these services through standard HTTP requests to achieve data integration and processing.

This is the end of this article about the implementation example of springboot calling python scripts. For more related contents of springboot calling python scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!