xuziwen127 2019-01-03 15:06 采纳率: 55.6%
浏览 5632
已采纳

spring boot项目中使用Runtime.exec()调用pyhton脚本没有反应

ubuntu环境下,在spring boot项目中使用Runtime.exec()去执行一个python脚本
没有反应,把这个执行命令单独拿出来执行是可以有结果的,而且把这段代码单独拿出
来写成一个java文件编译class去执行也可以执行pythone脚本;代码如下:

@RestController
@RequestMapping("/executescript")
public class ExecuteScript {

    @RequestMapping("/execpython")
    public Object execPython(){

        File file = new File("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py");

        if(file.exists()){
            System.out.println("可以读取到非项目中脚本");
        }else{
            System.out.println("不可以读取到非项目中脚本");
            return "不可以读取到非项目中脚本";
        }

        try {
            Runtime runTime = Runtime.getRuntime();

            runTime.exec("python2 /home/jysp/srr/RFCN-nanrui/tools/testXianjia.py");

            System.out.println("启动脚本");
        } catch (Exception e) {
            e.printStackTrace();
            return "执行python脚本失败";
        }

        return "执行python脚本成功";
    }
}

执行这段代码没有报任何错误,会返回"执行python脚本成功",我当时想了是不是spring boot项目不能直接执行python脚本,又把这行命令写到一个shell脚本中去,shell脚本单独执行也会有正确返回结果,可是把执行命令放入上述代码中执行,又出现没反应的结果


然后我又换了jython.jar的方式去调用,代码如下:

@RequestMapping("/execpython")
    public Object execPython(){

        File file = new File("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py");

        if(file.exists()){
            System.out.println("可以读取到非项目中脚本");
        }else{
            System.out.println("不可以读取到非项目中脚本");
            return "不可以读取到非项目中脚本";
        }


        PythonInterpreter interpreter = new PythonInterpreter();

        InputStream in = null;

        try {
            in = new FileInputStream("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py");

            PySystemState sys = Py.getSystemState();

            sys.path.add("/home/jysp/srr/RFCN-nanrui/tools");

            interpreter.exec("import _init_paths");

            interpreter.execfile(in);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "未找到文件";
        } catch (Exception e) {
            e.printStackTrace();

            if(null!=in){
                try {
                    in.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            return "执行python脚本失败";
        }

        return "执行python脚本成功";
    }

这次执行起来报错了,出现的异常是ImportError: No module named os:
图片说明
这是不是python环境变量的问题,java代码里要怎么去配置它的环境变量呢

python报ImportError: No module named os,我把那段python得代码贴出来

1  # --------------------------------------------------------
     2  # Fast R-CNN
     3  # Copyright (c) 2015 Microsoft
     4  # Licensed under The MIT License [see LICENSE for details]
     5  # Written by Ross Girshick
     6  # --------------------------------------------------------
     7
     8  """Set up paths for Fast R-CNN."""
     9
    10  import os.path as osp
    11  import sys
    12
    13  def add_path(path):
    14      if path not in sys.path:
    15          sys.path.insert(0, path)
    16
    17  this_dir = osp.dirname(__file__)
    18
    19  # Add caffe to PYTHONPATH
    20  caffe_path = osp.join(this_dir, '..', 'caffe', 'python')
    21  add_path(caffe_path)
    22
    23  # Add lib to PYTHONPATH
    24  lib_path = osp.join(this_dir, '..', 'lib')
    25  add_path(lib_path)

就是第十行import os.path as osp报的错,有谁知道这个os.path是在哪个路径下面得呀

  • 写回答

2条回答

  • 糕天原 2019-01-03 16:45
    关注

    尝试用 tputStream ops = process.getOutputStream();
    然后看ops里是什么

    Process process =  Runtime.getRuntime().exec("*****执行代码");
                        BufferedReader successResult = null;
            BufferedReader errorResult = null;
            StringBuilder successMsg = null;
            StringBuilder errorMsg = null;
             successMsg = new StringBuilder();
             errorMsg = new StringBuilder();
                    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String s;
                    while ((s = successResult.readLine()) != null) {
                        successMsg.append(s);
                    }
                    while ((s = errorResult.readLine()) != null) {
                        errorMsg.append(s);
                    }
                                    try {
                    if (os != null) {
                        os.close();
                    }
                    if (successResult != null) {
                        successResult.close();
                    }
                    if (errorResult != null) {
                        errorResult.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                if (process != null) {
                    process.destroy();
                }
    

    输出successMsg和errorMsg 特别是errorMsg

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler