python中使用正则模板匹配结果

正则配置处理类文件

util_tool.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Util Module for functionality shared between modules"""

import re

def combine_dicts(recs):
"""Combine a list of recs, appending values to matching keys"""
if not recs:
return None

if len(recs) == 1:
return recs.pop()

new_rec = {}
for rec in recs:
for k, v in rec.iteritems():
if k in new_rec:
new_rec[k] = "%s, %s" % (new_rec[k], v)
else:
new_rec[k] = v
return new_rec

class CommandParser(object):
"""Object for extending to parse command outputs"""

ITEM_REGEXS = []
ITEM_SEPERATOR = False
DATA = None
MUST_HAVE_FIELDS = []

def __init__(self, data, regexs=None, seperator=None):
self.set_data(data)
self.set_regexs(regexs)
self.set_seperator(seperator)

def set_data(self, data):
self.DATA = data.strip()

def set_regexs(self, regexs):
if regexs:
self.ITEM_REGEXS = regexs

def set_seperator(self, seperator):
if seperator:
self.ITEM_SEPERATOR = seperator

def parse_item(self, item):
rec = {}
for regex in self.ITEM_REGEXS:
matches = [m.groupdict() for m in re.finditer(regex, item)]
mdicts = combine_dicts(matches)
if mdicts:
rec = dict(rec.items() + mdicts.items())
return rec

def parse_items(self):
if not self.ITEM_SEPERATOR:
return [self.parse_item(self.DATA)]
else:
recs = []
for data in self.DATA.split(self.ITEM_SEPERATOR):
rec = self.parse_item(data)
recs.append(rec)
return recs

def parse(self):
if self.ITEM_SEPERATOR:
raise Exception("A seperator has been specified: '%s'. " + \
"Please use 'parse_items' instead")

return self.parse_item(self.DATA)

正则模板文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module for parsing the output of info"""

from util_tool import CommandParser

REGEX_TEMPLATE = r'\n%s\:([\ \t])+(?P<%s>.*)'
class CPUInfoParser(CommandParser):
ITEM_SEPERATOR = "\n\n"
ITEM_REGEXS = [
REGEX_TEMPLATE % (r'Model\ name', 'cpu_model'),
REGEX_TEMPLATE % (r'Socket\(s\)', 'cpu_sockets'),
REGEX_TEMPLATE % (r'Core\(s\)\ per\ socket', 'cpu_cores'),
REGEX_TEMPLATE % (r'CPU\(s\)', 'cpu_processors'),
REGEX_TEMPLATE % (r'CPU\ MHz', 'cpu_frequency'),
]

class CpuName(CommandParser):
ITEM_REGEXS = [
r'(.)*\ (?P<cpu_id>cpu[0-9]+)',
]

class EthernetParser(CommandParser):
ITEM_REGEXS = [
#r'(.)*\ (?P<net>eth[0-9]+)',
r'(.)*\ (?P<net>(((bond)|(eth))[0-9]+))\:',
r'(.)*link/ether\ (?P<mac>([0-9a-fA-F]{2})(([/\s:][0-9a-fA-F]{2}){5}))',
r'(.)*inet\ (?P<ipaddr>(\d{1,3}.){3}\d{1,3})',
r'(.)*Ethernet\ controller\:(?P<controller>.*)',
]



使用方法:
def get_cpu_freq_info(self):
"""
获取CPU每个核的频率并json化返回
:return:
"""
res = {}
try:
data = util.excute_command('ls -l /sys/devices/system/cpu/')
if data:
parser = reg_templates.CpuName(data)
rec = parser.parse()
if rec and isinstance(rec,dict):
if rec.has_key('cpu_id'):
cpuids = str(rec['cpu_id']).split(',')
for ci in cpuids:
if os.path.exists('/sys/devices/system/cpu/'+ str(ci).strip() +'/cpufreq/cpuinfo_cur_freq'):
result = util.excute_command(r'cat /sys/devices/system/cpu/'+ str(ci).strip() +'/cpufreq/cpuinfo_cur_freq')
if str(result).isdigit():
res[str(ci).strip()] = float(result)/1000000
else:
res[str(ci).strip()] = 'N/A'
else:
res[str(ci).strip()] = 'N/A'
return json.dumps(res, encoding="UTF-8", ensure_ascii=True)
except Exception as ex:
logger.exception("get_cpu_freq_info function execute exception:" + str(ex))

转载于:https://www.cnblogs.com/chmyee/p/9888103.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值