功能
从excel读入配置信息,根据预定义配置模板生成配置。功能虽然简单,但是要考虑通用性,配置模板改变时,不需要修改代码。
配置信息表格
第一行为设备名称,程序将以设备名称为文件名,写入设备配置。其余部分可以
配置文件包含配置模板信息
[intf_desc]
sheet = interface
intf_tempalte= template/inf_template.txt
template/inf_template.txt 内容如下:
interface {0[0]}
description {0[1]} {0[2]} {0[3]} {0[4]} {0[5]}
exit
excel读模块
class ExcelHandler:
def __init__(self, file):
self.file = file
def sheet_read(self, sheet):
xls_data_list = []
xls = xlrd.open_workbook(self.file)
table = xls.sheet_by_name(sheet)
nrows = table.nrows
for row_index in range(1,nrows):
xls_data_list.append(table.row_values(row_index))
return xls_data_list
配置生成模块和主函数
import configparser
from handler.excel_handler import ExcelHandler
config = configparser.ConfigParser()
config.read("etc/config.ini")
intf_des = config["intf_desc"]["desc"]
sheet = config["intf_desc"]["sheet"]
inf_template = config["intf_desc"]["intf_tempalte"]
class ConfigGenerate:
def __init__(self):
pass
@staticmethod
def replace_generate(data, template, file_name):
"""
:param data: configuration information
:param template: config template
:param file_name: destination file
:return:
"""
intf_config = template.format(data[1:7])
with open(file_name, 'a') as file:
file.write(intf_config+'\n')
if __name__ == "__main__":
config = ConfigGenerate()
excel_inst = ExcelHandler("config_inform.xlsx")
intf_data = excel_inst.sheet_read("interface")
with open(inf_template, 'r') as f:
intf_template = f.read()
for row in intf_data:
config.replace_generate(row, intf_template, row[0])
程序运行后,会生成以pe1,pe2,pe3,pe4,pe5,pe6 的文件。