导航

实现功能:

日志文件分析,找出包含关键字的行,并写入到新的文件中;
逐行匹配,关键字可以同时传入多个(使用“|”分割),也可以一行匹配多个关键字(使用&分割)

例如: > analysislog java|python&2.7
就会找出包含java的行,并写入java.log文件中;还会找出包含python并且包含2.7关键字的行,并写入python&2.7.log的文件中

 1 #-*- coding:utf8 -*-
 2 
 3 import os, sys, time
 4 
 5 
 6 def analysislog(filepath, keyword):
 7     if not os.path.exists(filepath):
 8         print "File not found !"
 9         raw_input("")
10         sys.exit()
11 
12     keywordlist = keyword.split("|")
13     fileobjlist = {}
14     for key in keywordlist:
15         fileobjlist[key] = open(key+".log", 'w')
16     
17     logfile = open(filepath, 'r')
18     
19     while 1:
20         logline = logfile.readline()
21 
22         if logline == "":
23             break
24 
25         for key in keywordlist:
26             if key.find("&") <> -1:
27                 andkeylist = key.split("&")
28                 andflag = 1
29                 for andkey in andkeylist:
30                     if logline.find(andkey) == -1:
31                         andflag = 0
32                 if andflag:
34                     fileobjlist[key].write(logline)
35 
36             else:
37                 if logline.find(key) <> -1:
39                     fileobjlist[key].write(logline)
40     for key in keywordlist:
41         fileobjlist[key].close()
42 
43 
44     logfile.close()
45 
46 
47 def appendtonewfile(logstr, newlogname):
48     newlogfile = open(os.path.join(os.getcwd(), newlogname),"a")
49 
50     newlogfile.write(logstr)
51 
52     newlogfile.close
53 
54 
55 
56 if __name__ == "__main__":
57     if len(sys.argv) == 1 :
58         logfilepath = raw_input("Please input the path of the log -> ")
59         keywords = raw_input("Please input the keywords(split by |) -> ")
60     elif len(sys.argv) == 2 :
61         logfilepath = sys.argv[1]
62         keywords = raw_input("Please input the keywords(split by |) -> ")
63     elif len(sys.argv) == 3 :
64         logfilepath = sys.argv[1]
65         keywords = sys.argv[2]
66     else :
67         print "Illegal Parameters...\n    AnalysisLog.py [logpath] [keywords] "
68         raw_input("")
69         sys.exit()
70 
71     
72     print "Log Path: %s"%logfilepath
73     print "Keywords: %s"%keywords.replace("|", " ")
74     
75     starttime = time.time()
76     analysislog(logfilepath, keywords)
77     endtime = time.time()
78     print "Time used: ",(endtime - starttime)," s"
79         
80         

 

PS: 可以使用 pyinstall 打包成exe程序。