为这个拖了很久的问题道歉。
我正在尝试读入一个配置文件,并获取一个规则列表。我曾尝试使用ConfigParser来做这件事,但它不是一个标准的配置文件。该文件不包含节头和标记。
即
配置部分a
将某物设置为另一物
配置小节a
将这个设置为那个
下一步
结束配置防火墙策略
编辑76
设置srcintf "There“
将dstintf设置为"Here“
set srcaddr "all“set dstaddr "all”set action accept set schedule "always“
设置服务"TCP_5600“
下一步
编辑77
将srcintf设置为"here“
设置dstintf "there“
将srcaddr设置为"all“
将dstaddr设置为"all“
设置操作accept
将计划设置为“始终”
设置服务"PING“
下一端
因为我不知道如何让ConfigParser工作,所以我想我应该试着遍历这个文件,不幸的是我没有太多的编程技能,所以我被卡住了。我真的觉得我把事情搞得太复杂了。这是我写的代码;
class Parser(object):
def __init__(self):
self.config_section = ""
self.config_header = ""
self.section_list = []
self.header_list = []
def parse_config(self, fields): # Create a new section
new_list = []
self.config_section = " ".join(fields)
new_list.append(self.config_section)
if self.section_list: # Create a sub section
self.section_list[-1].append(new_list)
else: self.section_list.append(new_list)
def parse_edit(self, line): # Create a new header
self.config_header = line[0]
self.header_list.append(self.config_header)
self.section_list[-1].append(self.header_list)
def parse_set(self, line): # Key and values
key_value = {}
key = line[0]
values = line[1:]
key_value[key] = values
if self.header_list:
self.header_list.append(key_value)
else: self.section_list[-1].append(key_value)
def parse_next(self, line): # Close the header
self.config_header = []
def parse_end(self, line): # Close the section
self.config_section = []
def parse_file(self, path):
with open(path) as f:
for line in f:
# Clean up the fields and remove unused lines.
fields = line.replace('"', '').strip().split(" ")
if fields[0] == "set":
pass
elif fields[0] == "end":
pass
elif fields[0] == "edit":
pass
elif fields[0] == "config":
pass
elif fields[0] == "next":
pass
else: continue
# fetch and call method.
method = fields[0]
parse_method = "parse_" + method
getattr(Parser, parse_method)(self, fields[1:])
return self.section_list
config = Parser().parse_file('test_config.txt')
print config
我正在寻找的输出类似于以下内容;
[[‘节a',{’东西‘:’到其他东西‘},’子节a',{‘这个’:‘到那个’}],[‘防火墙策略’,'76',{‘srcintf’:‘那里’},{‘dstintf’:‘此处’}{等}{等}]]
这就是我得到的
[‘a节’]
编辑
我已经更改了上面的内容,以反映我目前所处的位置。我仍然在获取我期望的输出时遇到问题。我就是不能把单子写对。
https://stackoverflow.com/questions/7552364
复制相似问题