所有,我编写了一个小的python脚本来从日志文件中解析出数据。我能够解析出我所需要的。现在,我正在尝试创建一个菜单,以便用户可以选择要解析的数据,而不是所有日志内容。我在尝试弄清楚如何做时有些挣扎,请有人帮我开始制作菜单。我是Python的新手。
这是我到目前为止所拥有的:
import re
with open('temp.log') as f:
lines = f.readlines()
data = []
for line in lines:
date = re.match(r'\d{2} \w+ \d{2}', line).group()
time = line.split()[3]
ids = line.split()[4]
try:
agent = re.search(r'agent:\s(.*?),', line).group()
except:
agent = 'agent:'
try:
errID = re.search(r'ErrIdText:\s(.*?),', line).group()
except:
errID = 'ErrIdText:'
try:
clear = re.search(r'clearedID:\s(.*?)\)', line).group()
except:
clear = 'clearedID:'
row = [date, time, ids, agent, errID, clear]
data.append(row)
for row in data:
print(row)
所以我想制作一个菜单,以便用户可以选择是否只想解析日期和座席名称。
答案 0 :(得分:1)
您可以使用click通过命令行来实现菜单。它将解析参数,您将能够过滤掉操作。对于简单的东西也很容易理解和实现。例如:
import re
import click
date_pattern = re.compile(r'\d{2} \w+ \d{2}')
agent_pattern = re.compile(r'agent:\s(.*?),')
err_pattern = re.compile(r'ErrIdText:\s(.*?),')
clear_pattern = re.compile(r'clearedID:\s(.*?)\)')
@click.command()
@click.option('--filter-agent', is_flag=True, default=False, help='Filter agent')
@click.option('--filter-err-id', is_flag=True, default=False, help='Filter Error ID')
@click.option('--filter-cleared-id', is_flag=True, default=False, help='Filter Cleared ID')
@click.argument('filename')
def get_valid_rows(filter_agent, filter_err_id, filter_cleared_id, filename):
with open(filename) as f:
lines = f.readlines()
data = []
for line in lines:
date = date_pattern.match(line).group()
time = line.split()[3]
ids = line.split()[4]
row = [date, time, ids]
if filter_agent:
try:
agent = agent_pattern.search(line).group()
except:
agent = 'agent:'
row.append(agent)
if filter_err_id:
try:
errID = err_pattern.search(line).group()
except:
errID = 'ErrIdText:'
row.append(errID)
if filter_cleared_id:
try:
clear = clear_pattern.search(line).group()
except:
clear = 'clearedID:'
row.append(clear)
data.append(row)
# Do everything else
if __name__ == "__main__":
get_valid_rows()
它甚至会为您生成格式正确的帮助消息
Usage: parselog.py [OPTIONS] FILENAME
Options:
--filter-agent Filter agent
--filter-err-id Filter Error ID
--filter-cleared-id Filter Cleared ID
--help Show this message and exit.
您可以根据自己的喜好对其进行编辑,以实现所需的功能。
答案 1 :(得分:0)