【springboot+python】 尝试springboot调用python的demo
尝试springboot调用python的demo
·
只是一个尝试demo
python代码
import sys
def detect(path):
print("python running:")
return "python result:"+path
if __name__ == '__main__':
# 参数从argv的第二个元素开始,第一个元素是运行的程序名
path = sys.argv[1]
print(detect(path))
springboot的controller
@RestController
public class DetectController {
@GetMapping
public void detect(HttpServletRequest request){
String path = request.getAttribute("path").toString();
try {
// 一维数组,第二个参数是文件的路径,后面的是python代码的参数
// 我猜是通过命令行指令?
String[] args = new String[]{"python","D:\\pycharm_project\\test\\lungDetect\\detect.py",path};
// 执行py文件
Process process = Runtime.getRuntime().exec(args);
// 获取输出的结果(打印在控制台的字符?)
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = in.readLine();
while(line!=null){
// 显示结果
System.out.println("springboot执行python结果:"+line);
line = in.readLine();
}
in.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("controller任务已完成");
}
}
springboot的测试用例
@SpringBootTest
class DetectControllerTest {
DetectController detectController;
@Autowired
public void setDetectController(DetectController detectController) {
this.detectController = detectController;
}
@Test
void detect() {
HttpServletRequest request = new MockHttpServletRequest();
request.setAttribute("path","www.heguchangan.xyz");
detectController.detect(request);
}
}
结果

原理
猜想是java通过使用命令行执行执行python xxx.py,来执行python文件,然后将打印出来的结果读取到io中在打印出来。具体原理待学习。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)