在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;