如果正则表达式匹配,则向消息添加文件路径

我有以下 Python 脚本(摘录如下),它读取 E:\Data\Production 目录下的所有日志文件并查找某些正则表达式匹配项。


errors, tr, warnings = [], [], []


rootdir = 'E:\\Data\\Production'


for folder, dirs, files in os.walk(rootdir):

    for file in files:

        if file.endswith('.log'):

            fullpath = os.path.join(folder, file)

            with open(fullpath, 'r') as f:

                for line in f:

                    for match in re.finditer(r'.*' + daysdate + '(?!.*[->OK].*).*[Ee]rror.*', line):

                        errors.append(match.group(0))

                    for match in re.finditer(r'.*' + daysdate + '.*(?!.*deployed)(?!.*complete.*)(?!.*There are no.*)(?!.*disabled.*).*TR\d{4}.*', line):

                        warnings.append(match.group(0))

                    for match in re.finditer(r'.*' + daysdate + '.*(?!.*deployed)(?!.*[->OK])(?!.*complete.*)(?!.*There are no.*)(?!.*disabled.*).*TR\d{4}.*', line):

                        tr.append(match.group(0))


if errors == []:

    errors.append("No errors found.")

[...]

sendmail():

    "Errors:\n\n%s\n" % "\n".join(map(str, errors)) +

    "\Faulty:\n\n%s\n" % "\n".join(map(str, tr)) +

    "\Warnings:\n\n%s\n" % "\n".join(map(str, warnings))

sendmail()

这个的输出是:


Errors:

No errors found.

Faulty:

<the entire line containing the matched regex>

Warnings:

No errors found.

我想要做的是添加发现错误的日志文件的完整路径,因此它会改为:


Errors:

No errors found.

Faulty:

<the entire line containing the matched regex>

Error found in file: E:\Data\Production\qwer\asdf\zxcv.log

Warnings:

No warnings found.

我假设我需要以某种方式附加 fullpath 变量,但我不知道如何实现它。


侃侃无极
浏览 133回答 1
1回答

拉丁的传说

我相信你需要。for&nbsp;match&nbsp;in&nbsp;re.finditer(r'.*'&nbsp;+&nbsp;daysdate&nbsp;+&nbsp;'.*(?!.*deployed)(?!.*[->OK])(?!.*complete.*)(?!.*There&nbsp;are&nbsp;no.*)(?!.*disabled.*).*TR\d{4}.*',&nbsp;line): &nbsp;&nbsp;&nbsp;&nbsp;tr.append(match.group(0)&nbsp;+&nbsp;"\n{0}".format(fullpath))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python