赞
踩
只是一个尝试demo
import sys
def detect(path):
print("python running:")
return "python result:"+path
if __name__ == '__main__':
# 参数从argv的第二个元素开始,第一个元素是运行的程序名
path = sys.argv[1]
print(detect(path))
@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任务已完成"); } }
@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中在打印出来。具体原理待学习。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。