2010-05-13 57 views
0

我在我的代碼中使用這個函數來返回我想從讀取日誌文件中得到的字符串,我想grep「exim」過程並返回結果,但運行代碼時沒有提供任何錯誤,但產量只有三行,我如何才能獲得只涉及到進出口過程中的輸出..python logparse搜索特定文本

#output: 
    {'date': '13', 'process': 'syslogd', 'time': '06:27:33', 'month': 'May'} 
    {'date': '13', 'process': 'exim[23168]:', 'time': '06:27:33', 'month': 'May'} 
    {'May': ['syslogd']} 


#function:  
def generate_log_report(logfile): 
    report_dict = {} 
    for line in logfile: 
     line_dict = dictify_logline(line) 
     print line_dict 
     try: 
      month = line_dict['month'] 
      date = line_dict['date'] 
      time = line_dict['time'] 
      #process = line_dict['process'] 
      if "exim" in line_dict['process']: 
       process = line_dict['process'] 
       break 
      else: 
       process = line_dict['process']  
     except ValueError: 
      continue 
     report_dict.setdefault(month, []).append(process) 
    return report_dict 

回答

0

我改變了這個代碼,但它只給我一行作爲輸出?遺漏...

#!/usr/bin/env python 

import sys 

def generate_log_report(logfile): 
     for line in logfile: 
       line_split = line.split() 
       list = [line_split[0], line_split[1], line_split[2], line_split[4]] 
       if "exim" in list[3]: 
         l = [line_split[0], line_split[1], line_split[2], line_split[4]] 
       else: 
         li = [line_split[0], line_split[1], line_split[2], line_split[4]] 
     return l 


if __name__ == "__main__": 
     if not len(sys.argv) > 1: 
       print __doc__ 
       sys.exit(1) 
     infile_name = sys.argv[1] 
     try: 
       infile = open(infile_name, "r") 
     except IOError: 
       print "you must specify a valid file" 
       print __doc__ 
       sys.exit(1) 
     log_report = generate_log_report(infile) 
     print log_report 
     infile.close() 
+0

我加入 「打印L」 else子句前和工作!但我不明白爲什麼「RETURN L」沒有工作... – krisdigitx 2010-05-14 10:33:46

0

這是因爲你有裏面的break語句如果檢查「進出口」。只要你找到「exim」的一行,你就會完全停止處理,這聽起來就像你想要的相反!

我想你想刪除中斷並把你的打印輸出到if中。如果您的問題是關於函數的返回值,那麼您需要做出更重要的更改,可能完全刪除report_dict並簡單地創建一個在其進程字段中具有exim的列表。