用于从日志文件提取测试的Python脚本

2024-06-24 12:16:00 发布

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

问题陈述如下,有日志文件包含与测试结果相关的日志。例如,它包含文本,比如testcase1后跟测试用例的日志,testcase2后跟测试用例的日志等等。你知道吗

若用户想要提取testcase1和testcase3的日志,脚本应该读取来自用户的输入,比如testcase1和testcase3。然后只提取指定测试用例的日志。你知道吗

在这种情况下,假设用户输入testcase1和testcase3,输出应该是日志文件中testcase1和testcase3下面的行。你知道吗


Tags: 文件用户文本脚本情况测试用例testcase1testcase2
2条回答

最后得到了提取文本的工作脚本

#从文本文件中读取特定行 #例如,在程序中,我们读取文件并只打印标题2和标题4下的行 #日志文件可能包含空行 #示例日志文件 #职务 # 1 #dklfjsdkl公司; #克 #sdfzsdfsdf公司 #sdfsdfsdf公司 #dsfsdfsd公司 #dfsdf公司 # #职务 # 2 # #dfdf公司 #dfdf公司 #dfdf公司 #测向 #dfd公司 #d级 # #标题3 #sdfdfd公司 #DFD公司 #dfd公司 # #dfd公司 # #职务 # 4 #dfkdfkd公司 #dfdkjmd公司 #dfdkljm公司

in_list= []
while True:
    i = raw_input("Enter title to be extracted (or Enter to quit): ")
    in_list.append(i)
    if not i:
        break

    print("Your input:", i)
print("While loop has exited")
in_list.remove(i)
print "Input list", in_list

flist = []
with open("C:\\text.txt", 'r') as inp:
    #read the flie and storing into the list
    flist =inp.readlines()
    inp.close()

#making everything in the list to lower case
flist = map(lambda x:x.lower(),flist)
flist = [s.strip("\n") for s in flist]
print flist

    # printing the complete log file from the list. Since once we put the vlaue in the list the new line character will be \ appended in the list element.
    #hence striping with \n character
# for i in flist:
#     print i.strip("\\n")

for j in range(len(in_list)):
    result = any(in_list[j] in word for word in flist)
    if result:
        i_index = flist.index(in_list[j])
        flag = 0
        with open("C:\\output.txt",'a') as f1:
            f1.write(flist[i_index])
            f1.write("\n")

            while flag ==0:
                if "title" in flist[i_index+1]:
                    flag =1
                else:
                    i_index += 1
                    f1.write(flist[i_index])
                    f1.write("\n")
                    i_index += 1

f1.close()

在这里,您必须假设所有testcase日志都在单独的行中,这意味着您在每个日志行后面都有'\n'。你知道吗

然后可以从linecache模块读取文件。 现在,您应该以特定的格式创建日志。在这里,您提到它是[testcaseN][Log message],并且[testcaseN]应该有'testcase'和'N'作为变量。你知道吗

因此,当您使用linecache模块获取所有行时,请使用re模块将作为输入的testcaseN与获取的单个行的第一个字进行匹配。一旦找到匹配项,就显示结果。你知道吗

相关问题 更多 >