@Controller
public class IndexController {
@RequestMapping("/pythonTest")
@ResponseBody
public String pythonTest(){
// 假设你的Python脚本名为script.py
String pythonScriptPath = "D:\\project\\c1\\hello.py";
ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath);
processBuilder.redirectErrorStream(true);
String lines="";
try {
Process process = processBuilder.start();
// 读取Python脚本的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
lines+=line;
}
// 等待Python脚本执行完成
int exitCode = process.waitFor();
if (exitCode != 0) {
System.out.println("Python script exited with error code: " + exitCode);
}
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return lines;
}
}
hello.py
def say_hello():
print("hello")
if __name__=="__main__":
say_hello()