python - 将列表解析为另一个函数参数 - Python

标签 python function text

我有一个 .log 文件,我想检查其中是否有错误/警告:

    2018-03-05 10:55:54,636 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M740.aswc.arxml is well-formed
    2018-03-05 10:55:55,193 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M740.aswc.arxml is valid with the AUTOSAR4.2.2-STRICT schema
    2018-03-05 10:55:55,227 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M741.aswc.arxml is well-formed
    2018-03-05 10:55:55,795 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M741.aswc.arxml is valid with the AUTOSAR4.2.2-STRICT schema
    2018-03-05 10:55:55,831 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M742.aswc.arxml is well-formed
    2018-03-05 10:55:56,403 INFO The file: C:/test/Abu/TRS.ABU.GEN.003_1/input\ASWC_M742.aswc.arxml is valid with the AUTOSAR4.2.2-STRICT schema
    2018-03-05 10:55:56,438 WARNING ASWC_M740_MSI is without connector
2018-03-05 10:55:56,438 ERROR ASWC_M741_MSI is without connector
    2018-03-05 10:55:56,438 WARNING PRP_CS_VehicleSPeed is without connector

到目前为止,我已经成功编写了下一个函数,但没有成功:

def checkLog(path, level, message):
    """
    path = used for defining the file to be checked
    level = criticity level :INFO, WARNING, ERROR
    message = string to be matched
    """
    datafile = open(path)
    line_file = datafile.readline()
    while line_file != "":
        for text in message:
            if level + " " + text in line_file:
                return True
            line_file = datafile.readline()
    return False

checkLog("C:\\test\Abu\TRS.ABU.GEN.003_1\output\\result.log", "WARNING", ["PRP_CS_VehicleSPeed", "ASWC_M740_MSI", "ASWC_M741_MSI"])

我哪里错了?

最佳答案

第二个 readline() 位于 for 循环内,它迭代可能要匹配的消息,因此在检查所有消息之前代码会移至下一行。

尝试将其移至外部范围:

def checkLog(path, level, message):
    datafile = open(path)
    line_file = datafile.readline()
    while line_file != "":
        for text in message:
            if level + " " + text in line_file:
                return True
        line_file = datafile.readline()
    return False

你的代码可以更好地写成这样:

def checkLog(path, level, message):
    with open(path) as datafile:
        for line in datafile:
            for text in message:
                if (level + " " + text) in line:
                    return True
    return False

这避免了调用readline(),而是迭代文件对象,从而简化了代码。它还使用上下文管理器(with 语句)打开文件,这将确保文件正确关闭。

关于python - 将列表解析为另一个函数参数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107512/

相关文章:

python - 如何使用 Bokeh 添加共享 x 轴的额外子图?

python - 将命令行输出导出到 Python 中的文件

javascript - 如何在 Javascript 中从外部作用域调用函数?

c# - 如何获取长字符串并将其滚动到 15 个字符的文本控件/标签中?

python - 通过 MySQLdb 添加 SQL 变量

python - 相同的代码不同的结果

c++ - 在 C++ 中传递带有参数的函数

ASP.NET GridView TemplateField 调用函数( :int)

iOS:电子书的大量交互式文本

python - 消除多余的逗号