• Java调用Python脚本并获取返回值


    在Java程序中有时需要调用Python的程序,这时可以使用一般的PyFunction来调用python的函数并获得返回值,但是采用这种方法有可能出现一些莫名其妙的错误,比如ImportError。在这种情况下可以采用另一种方法:使用Java的Runtime,像在命令行直接调用python脚本那样调用python程序。此时可以通过文件作为脚本参数来传递Python程序所需要的参数,并从脚本的输入输出流来获取本来该打印在控制台的结果。

    先准备好一个python文件:

    def get_path(filename):
        y_t = np.loadtxt(filename)
        peolpex = int(y_t[0][0])
        peolpey = int(y_t[0][1])
        firex = int(y_t[1][0])
        firey = int(y_t[1][1])
    
        answer = getQ(peolpex, peolpey, firex, firey)
        return answer
    
    
    if __name__ == "__main__":
        filename = sys.argv[1]
        # print(filename)
    
        # root = Tk()
        # canvas = Canvas(root, bg="white")
        # canvas.pack()
        # colors = ['red', 'orange',  'green', 'black','yellow','white','pink']
    
        result = get_path(filename)
        # with open(filename, 'w') as f:
        #     f.write(result)
        print result

    对应的Java程序如下:

    String result = "";
    
            try {
                Process process = Runtime.getRuntime().exec("python /home/jia/fireevacuation/my.py " + filename);
    //            process.waitFor();
                InputStreamReader ir = new InputStreamReader(process.getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                result = input.readLine();
                input.close();
                ir.close();
    //            process.waitFor();
            } catch (IOException e) {
                logger.error("调用python脚本并读取结果时出错:" + e.getMessage());
            }
            return result;
  • 相关阅读:
    浏览器内核
    为什么一般请求可以下载文件,Ajax 请求就不能下载
    转 深入理解javascript原型和闭包(10)——this
    node读取文本文件时,去掉BOM
    AMD & CMD
    gulp requirejs Error: ENOENT: no such file or directory, open '/js/require_config.js', 一直报找不到require_config.js,坑死了
    [BZOJ3224]普通平衡树
    [NOIP2014D2]
    [NOIP2014D1]
    [NOIP2013D2]
  • 原文地址:https://www.cnblogs.com/sumuncle/p/9142193.html
Copyright © 2020-2023  润新知