2017-07-12 29 views
0

私は任意の数の行とjson文字列を持つログファイルを持っています。私が必要とするのは、ログファイルから「_____GP D_____」の後に1つのjsonデータを抽出することだけです。私はファイルから他の行やjsonデータを望んでいません。Pythonでログファイルを解析する

これは私の入力ファイルは、私が唯一の「_____GP D_____」の後にJSON文字列を見つけるのですか

INFO:modules.gp.helpers.parameter_getter:_____GP D_____ 
{'from_time': '2017-07-12 19:57', 'to_time': '2017-07-12 20:57', 'consig_number': 'dup1', 'text': 'r155', 'mobile': None, 'email': None} 
ERROR:modules.common.actionexception:ActionError: [{'other': 'your request already crossed threshold time'}] 
{'from_time': '2016-07-12 16:57', 'to_time': '2016-07-12 22:57', 'consig_number': 'dup2', 'text': 'r15', 'mobile': None, 'email': None} 

をどのように見えるかありますか?

答えて

0

あなたが_____GP D_____に遭遇するまで、あなたが行の末尾にラインで自分のファイルの行を読み取ることができ、そしてあなただけの次の行拾う行うとき:

found_json = None 
with open("input.log", "r") as f: # open your log file 
    for line in f: # read it line by line 
     if line.rstrip()[-14:] == "_____GP D_____": # if a line ends with our string... 
      found_json = next(f).rstrip() # grab the next line 
      break # stop reading of the file, nothing more of interest 

を、あなたは何でもあなたのfound_jsonで行うことができますあなたが継続的に使用すると、読み取りモードで開き、開いているファイルハンドルを維持することができます(tail -fコマンドに似て)あなたのログファイルを「従う」にしたい場合 -

UPDATEなど、それを印刷し、それを解析するなど、欲しいですそれを1行ずつ読みながらあなたが望む行がいつ発生したのかを発見し、処理する次の行をキャプチャしたり、他のプロセスに送信したり、何をやろうとしていても、同じ手順を使って読み込み間に追加することができます(tail -f)それと。ような何か:

import time 

capture = False # a flag to use to signal the capture of the next line 
found_lines = [] # a list to store our found lines, just as an example 
with open("input.log", "r") as f: # open the file for reading... 
    while True: # loop indefinitely 
     line = f.readline() # grab a line from the file 
     if line != '': # if there is some content on the current line... 
      if capture: # capture the current line 
       found_lines.append(line.rstrip()) # store the found line 
       # instead, you can do whatever you want with the captured line 
       # i.e. to print it: print("Found: {}".format(line.rstrip())) 
       capture = False # reset the capture flag 
      elif line.rstrip()[-14:] == "_____GP D_____": # if it ends in '_____GP D_____'.. 
       capture = True # signal that the next line should be captured 
     else: # an empty buffer encountered, most probably EOF... 
      time.sleep(1) # ... let's wait for a second before attempting to read again... 
+0

私は、継続的かついつでもこの「_____GP D_____」に関するログを読んで発生したと私はRabbitMQの中で多分それを保存し、それを処理することができますどのように任意のアイデア、?または、私はログファイル内で一意である複数のjson文字列を選択する必要がある場合は? –

+0

@PritishKRoy - 上記のアップデートを確認してください。 – zwer

+0

https://stackoverflow.com/questions/45087630/python-parse-from-log-file –

関連する問題