Source code for perfmon.common.utils.parsing
"""Utility functions for parsing"""
import re
import logging
import argparse
_log = logging.getLogger(__name__)
# pylint: disable=E0401,W0201,C0301
[docs]class RawFormatter(argparse.HelpFormatter):
"""
Class SmartFormatter prints help messages without any formatting
or unwanted line breaks, acivated when help starts with R|
"""
def _split_lines(self, text, width):
if text.startswith('R|\n'):
text = text[3:].rstrip()
lines = text.splitlines()
first_indent = len(lines[0]) - len(lines[0].lstrip())
return [l[first_indent:] for l in lines]
elif text.startswith('R|'):
return [l.lstrip() for l in text[2:].strip().splitlines()]
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
[docs]def get_parser(cmd_output, reg="lscpu"):
"""Regex parser.
Args:
cmd_output (str): Output of the executed command
reg (str): Regex pattern to be used
Returns:
Function handle to parse the output
"""
def parser(pattern):
"""Parser function."""
# Different regex for parsing different outputs
if reg == 'perf':
exp = r'(?P<Value>[0-9,]*\s*)(?P<Field>{}.*)'.format(pattern)
elif reg == 'perf-intvl':
exp = (
r'(?P<Time>[0-9.]*\s*)'
r'(?P<Value>[0-9,><a-zA-Z\s]*\s*)'
r'(?P<Field>{}.*)'.format(pattern)
)
else:
exp = r'(?P<Field>{}:\s*\s)(?P<Value>.*)'.format(pattern)
# Search pattern in output
result = re.search(exp, cmd_output)
try:
# Get value of the group if found
return result.group('Value')
except AttributeError:
# _log.debug('Parsing = %s | Field = %s | Value = %s', reg,
# pattern, 'None')
# If not found, return 'not_available'
return 'not_available'
return parser