Python中的快速.gz日志文件解析

2024-03-29 09:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个日志文件,其中包含10000多行信息和gzip。我需要一种方法来快速解析每个日志文件中的相关信息,然后根据所有日志文件中包含的信息显示统计信息。我目前使用gzip.open()递归地打开每个.gz文件,然后通过原语解析器运行内容。你知道吗

def parse(logfile):
    for line in logfile:
        if "REPORT" in line:
            info = line.split()
            username = info[2]
            area = info[4]
            # Put info into dicts/lists etc.
        elif "ERROR" in line:
            info = line.split()
            ...

def main(args):
    argdir = args[1]
    for currdir, subdirs, files in os.walk(argdir):
        for filename in files:
            with gzip.open(os.path.join(currdir, filename), "rt") as log:
                parse(log)
    # Create a report at the end: createreport()

是否有任何方法可以为每个文件优化此过程?目前,我的电脑上每个文件都需要28秒才能通过每个.gz,每一点优化都很重要。我试过使用pypy,但由于某些原因,处理一个文件要花2倍的时间。你知道吗


Tags: 文件方法ininfo信息forparsedef