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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章