SoFunction
Updated on 2025-04-22

One article will help you understand how to easily call Python scripts in Spring Boot

Cross-language calls are becoming more common in modern development, especially when you want to combine the advantages of different technology stacks. For example, Spring Boot is a very popular Java development framework, often used to build high-performance backend applications. Python is very popular in fields such as data analysis, machine learning, and automation tasks due to its simplicity and rich scientific computing library. So, how to call Python scripts in Spring Boot and take advantage of these two? Today we will use a specific example to teach you how to call Python scripts in Spring Boot applications.

Preface: Requirements background for cross-language calls

Many times, our applications may need to deal with some complex tasks, such as data analysis, inference of machine learning models, etc. Although Spring Boot is very suitable for developing high-performance web applications, it does not have as rich scientific computing libraries as Python in its ecosystem. Therefore, the ideal solution is to combine Spring Boot and Python to complete Python-specific tasks by calling Python scripts.

Step 1: Prepare Python scripts

First, you need to prepare a Python script. Here we take a simple Python script as an example, assuming that this script is used to calculate the sum of two numbers:

# 
import sys
 
def calculate_sum(a, b):
    return a + b
 
if __name__ == '__main__':
    # Get the parameters passed by the command line    num1 = int([1])
    num2 = int([2])
    
    result = calculate_sum(num1, num2)
    
    # Print the results    print(result)

In this example, the script takes two command line parameters, calculates their sum, and prints the result. You can expand this script according to your needs, such as calling machine learning models, performing data processing, etc.

Make sure you have the Python environment installed and can run the script successfully on the command line. You can test the script with the following command:

python  3 5

This command should output 8.

Step 2: Call Python scripts in Spring Boot project

In Spring Boot applications, we can use ProcessBuilder to execute external commands (such as executing Python scripts). ProcessBuilder allows us to start a new process and interact with it (such as getting output, passing input, etc.). Let's take a look at how to call Python scripts in Spring Boot.

2.1 Creating a Spring Boot Project

First, you need to create a Spring Boot project. You can use Spring Initializr to generate projects:/

Select appropriate project metadata, such as Group, Artifact, etc.

Select Spring Web as the dependency.

Download and import the generated project to your IDE (such as IntelliJ IDEA or Eclipse).

2.2 Create a Service class that calls Python scripts

Next, we create a Service class in our Spring Boot application to call Python scripts:

package ;
 
import ;
import ;
import ;
 
@Service
public class PythonScriptService {
 
    public String executePythonScript(int num1, int num2) {
        try {
            // Build ProcessBuilder to execute Python scripts            ProcessBuilder processBuilder = new ProcessBuilder("python", "path/to/", (num1), (num2));
            (true);
 
            // Start the process and get the output            Process process = ();
 
            // Read the output of Python scripts            BufferedReader reader = new BufferedReader(new InputStreamReader(()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = ()) != null) {
                (line).append("\n");
            }
 
            // Wait for the Python script to complete            ();
            return ().trim(); // Return the output of the Python script        } catch (Exception e) {
            ();
            return "Error executing Python script";
        }
    }
}

In the above code, we use ProcessBuilder to build a process to execute Python scripts. It should be noted that path/to/ should be replaced by the path you actually save the Python script. Additionally, we use BufferedReader to read the standard output of Python scripts.

2.3 Create Controller class to expose interface

Next, we create a Controller class and expose an interface to call the PythonScriptService above:

package ;
 
import ;
import ;
import ;
import ;
import ;
 
@RestController
public class PythonScriptController {
 
    @Autowired
    private PythonScriptService pythonScriptService;
 
    @GetMapping("/calculate")
    public String calculate(@RequestParam int num1, @RequestParam int num2) {
        // Call Python script        return (num1, num2);
    }
}

This Controller class defines a simple RESTful interface/calculate, which receives two query parameters num1 and num2, and executes Python scripts by calling PythonScriptService.

2.4 Start Spring Boot Application

Now, start Spring Boot application() and visit http://localhost:8080/calculate?num1=5&num2=3, you should be able to get the output of the Python script:

8

Step 3: Error handling and performance optimization

Error handling: In actual development, we need to add more error handling. For example, make sure that the parameters passed to the Python script are legal, check whether the Python script exists, capture the error output in the execution of the Python script, etc.

Performance optimization: A new process is started every time a Python script is called, which may affect performance. For frequent calls, consider encapsulating tasks in Python scripts into a service and using process pools to reuse processes.

Conclusion: Easily implement cross-language integration

Through the above steps, we have successfully called Python scripts in Spring Boot and implemented cross-language integration. Doing so can give full play to the advantages of Spring Boot in web development, while leveraging Python's powerful data processing and scientific computing capabilities to solve complex problems. Whether it is data analytics, machine learning, or automated scripting, the combination of Spring Boot and Python will bring you endless possibilities.

This is the article about this article about how to easily call Python scripts in Spring Boot. This is all about this article. For more related contents of Spring Boot 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!