我正在使用DHCP编辑器添加、删除和搜索主机。我有代码,将搜索和添加一个主机,我想我会以某种方式结合这两个删除一个主机,但没有工作。我想做的是创建元素索引f.readlines()
的列表,然后使用myindex to的值,然后从我正在编辑的DHCP文件运行lines.remove(myindex)
。你知道吗
示例我想搜索foonode
或任何节点并删除以下格式:
host barnode{
option host-name "barnode";
option root-path "0.0.0.0:/barnode";
option subnet-mask ;
option routers ;
hardware ethernet ;
fixed-address ;
}
host foonode{
option host-name "foonode";
option root-path "0.0.0.0:/foonode";
option subnet-mask ;
option routers ;
hardware ethernet ;
fixed-address ;
}
host foobarnode{
option host-name "foobarnode";
option root-path "0.0.0.0:/foobarnode";
option subnet-mask ;
option routers ;
hardware ethernet ;
fixed-address ;
}
我可以使用以下代码搜索文件:
def delete_host():
host=raw_input('Please enter host you would like to delete: ');
start = False;
f=open(infile, 'r')
myfile=str()
myindex=list()
mystr=str()
count = 0
lines = f.readlines()
for line in lines:
if re.search(host, line):
start = True
if start:
print line
myindex = [lines.index(line)]
if re.search('}', line):
break
得到这个输出:
host foonode{
option host-name "foonode";
option root-path "0.0.0.0:/foonode";
option subnet-mask ;
option routers ;
hardware ethernet ;
fixed-address ;
我想在搜索条件中为f.readlines()
的元素索引值创建索引列表。然后使用这些值执行lines.remove(myindex.index())
,以删除运行上述代码时获得的输出。基本上我如何搜索任何节点并从文件中删除它们。
也许创建一个索引并不是解决这个问题的最佳方法,我只是在google中搜索的表达式已经用完了。你知道吗
我知道我将不得不做newfile= open('/var/tmp/foodhcp' 'w')
,但我想在开始写文件之前把逻辑弄正确。你知道吗
老实说,我不明白上面的例子。我不停地摸索,得出了以下结论:我创建了一个列表,其中填充了搜索代码的输出。然后我想写每一行不等于我的索引。我很困惑
我还尝试创建一个元素列表,然后尝试使用del删除这些元素,但我一直遇到一个错误
我得到的错误
但是type返回int,所以我不明白我在做什么。你知道吗
如果已经有行列表,只需从要删除的行之前和之后的零件创建一个新的更新列表:
(请注意,检查缺少的主机名、格式不正确的主机名或带有可能干扰regexp的有趣符号的主机名时不会出错)。你知道吗
如果您确定所有的条目总是像您描述的那样(特别是,
}
不会在host
正文的任何地方遇到),您可以将其简化为最安全的方法是实际解析配置文件,获取数据结构,删除条目,然后创建一个新的配置文件。你知道吗
请注意,从正在循环的列表中删除项不会按预期的方式工作。我建议
a==[1,2,5]
您已经能够找到起始行和结束行,所以在找到它们之后运行del。你知道吗
相关问题 更多 >
编程相关推荐