Java調用Python腳本並獲取返回值

在Java程序中有時須要調用Python的程序,這時能夠使用通常的PyFunction來調用python的函數並得到返回值,可是採用這種方法有可能出現一些莫名其妙的錯誤,好比ImportError。在這種狀況下能夠採用另外一種方法:使用Java的Runtime,像在命令行直接調用python腳本那樣調用python程序。此時能夠經過文件做爲腳本參數來傳遞Python程序所須要的參數,並從腳本的輸入輸出流來獲取原本該打印在控制檯的結果。python

先準備好一個python文件:canvas

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;
相關文章
相關標籤/搜索