标签:gconf -- logs 实现 strip highlight ges 添加内容 evo
一、工作中遇到sed添加及修改在nginx末尾添加太麻烦了
需求:随意查找添加一条以前不存在的内容加到"}"前一行
实现:
#!/usr/bin/env python # coding=utf-8 import sys,os from optparse import OptionParser parse = OptionParser() parse.add_option("-c", "--context", help="add one line contexts",default="xxxhtxxxtps_status") parse.add_option("-f", "--file", help="modify file",default="/006_eleallproject/002_surveypro/001_nginxdevops/002_camel-agent-deploy/camel-agent-deploy2.0/nginx.conf") (options, args) = parse.parse_args() content = options.context file = os.path.realpath(options.file) #content="x$https_status" #file=‘/006_eleallproject/002_surveypro/001_nginxdevops/002_camel-agent-deploy/camel-agent-deploy2.0/nginx.conf‘ print options _list_content=[] m = 0 count = 0 #获取"}"的位置 try: fh = open(file, ‘rb‘) for n in fh.readlines(): m += 1 if (n.find(‘}‘) >= 0): global count count = m _list_content.append(n) else: _list_content.append(n) finally: fh.close() #在"}"位置前添加内容 n = 0 ngconf = open(file, ‘rb‘) for s in ngconf.readlines(): n += 1 if s.find(‘}‘) >= 0 and n >= count-1: #在以前的列表中有任何可以找到的内容都不会添加 result = any([str(line.strip()).find(content) >=0 for line in _list_content]) if not result: _list_content.insert(count-1, content+"\n") ngconf.close() #写入文件 end_nginx_f = open(file, ‘wb‘) end_nginx_f.writelines(_list_content) end_nginx_f.close()
标签:gconf -- logs 实现 strip highlight ges 添加内容 evo
原文地址:http://www.cnblogs.com/arun-python/p/7153562.html