如何在Spring Boot项目中调用Python脚本并获取其输出?
Sure thing! You don’t need any fancy third-party libraries—Java’s built-in ProcessBuilder is the perfect lightweight solution for this. It lets you spawn your Python command directly from Spring Boot and read its output (and errors) with minimal setup. Here’s a step-by-step implementation tailored to your scenario:
Step 1: Create a Reusable Service Component
First, build a Spring service to handle executing the Python script and fetching results. This keeps your code clean and reusable across your application:
import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; @Service public class PythonScriptExecutor { public String executePython(String... arguments) throws IOException { // Build the base command: python -m base-package List<String> command = new ArrayList<>(List.of("python", "-m", "base-package")); // Add any user-provided arguments to the command for (String arg : arguments) { command.add(arg); } ProcessBuilder processBuilder = new ProcessBuilder(command); // Optional: Set the working directory to your Python project's root // Use this if your Python package isn't in the same folder as your Spring Boot app // processBuilder.directory(new File("/path/to/your/python/project")); // Start the Python process Process process = processBuilder.start(); // Capture standard output from the Python script StringBuilder output = new StringBuilder(); try (BufferedReader outputReader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { String line; while ((line = outputReader.readLine()) != null) { output.append(line).append("\n"); } } // Capture error output (critical for debugging failed runs) StringBuilder errorLog = new StringBuilder(); try (BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream()))) { String line; while ((line = errorReader.readLine()) != null) { errorLog.append(line).append("\n"); } } // Wait for the process to finish and validate exit code try { int exitCode = process.waitFor(); if (exitCode != 0) { throw new IOException( String.format("Python script failed with exit code %d\nError details:\n%s", exitCode, errorLog.toString().trim()) ); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Python process was interrupted", e); } return output.toString().trim(); } }
Step 2: Use the Service in a Controller (Optional)
If you want to expose this functionality via a REST API, add a simple controller to handle requests:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class PythonCallerController { private final PythonScriptExecutor scriptExecutor; // Constructor injection (Spring's preferred method) public PythonCallerController(PythonScriptExecutor scriptExecutor) { this.scriptExecutor = scriptExecutor; } @GetMapping("/run-python-script") public String runScript(@RequestParam(value = "args", required = false) String[] args) throws IOException { return scriptExecutor.executePython(args); } }
Critical Things to Remember
- Python Path: Ensure
python(orpython3if you’re using Python 3 exclusively) is in the system PATH of the machine running your Spring Boot app. If not, use the full path to your Python executable (e.g.,/usr/bin/python3). - Security: Always sanitize user-provided arguments! Never pass unvalidated input directly to the command—this prevents command injection attacks.
- Working Directory: If your Python package isn’t in the same directory as your Spring Boot app, set the
directoryonProcessBuilderto point to your Python project’s root folder. - Error Handling: The example captures both standard output and error logs, which is essential for debugging if your Python script crashes or behaves unexpectedly.
That’s it! This is a no-frills, maintainable way to integrate your Python code with Spring Boot without any extra dependencies.
内容的提问来源于stack exchange,提问作者vineeth kumar

