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