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

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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?