腳本實作了一下功能:
- GetFileEndChange方法實作了對檔案追加内容的監控
- GetFileKeyInfo方法實作了對檔案關鍵字的檢索
- GetFileNewKeyData方法實作了對檔案追加的内容關鍵字的檢索
- 對互動的優化,實作了檢索檔案、檢索次數的統計
應用場景:
日志檔案管理
腳本
#coding:utf-8
"""
Note:
擷取檔案的改變
Author:redsun
Data:2019/7/10
"""
import re
import time
import os
def GetFileEndChange(File_Path):
'''
從檔案尾部開始檢查檔案追加的内容
:param File_Path: 路徑
:return: 輸出尾部增加的内容
'''
with open( File_Path ) as f:
f.seek(0,2)
cur = f.tell()
temp = 0
text = ''
HelpInfoHead('Change', File_Path, cur)
while True:
f.seek(cur)
ch = f.readlines()
# 如果沒有讀到資料,跳出循環
if not ch:
if HelpInfoEnd('Change',temp) == 'no':
break
else:
for line in ch:
text += line
HelpInfoContent(text, temp)
temp += 1
cur = f.tell()
def GetFileKeyInfo(File_Path, KeyWord):
'''
檢索檔案中與關鍵字相關的行,并輸出
:param File_Path: 檔案路徑
:param KeyWord: 關鍵字
:return: 輸出關鍵字所在的行
'''
with open(File_Path) as f:
lines = f.readlines()
if len(lines) == 0:
print("================日志檔案為空================")
else:
count = 0
text = ''
HelpInfoHead('KeyInfo', File_Path)
for line in lines:
rs = re.search(KeyWord, line)
if rs:
count += 1
text += line
HelpInfoContent(text)
print('[命中{count}次]'.format(count=count))
HelpInfoEnd('KeyInfo')
def GetFileNewKeyData(File_Path, KeyWord):
'''
檢索檔案尾部新增内容關鍵字比對,并輸出結果
:param File_Path: 檔案路徑
:param KeyWord: 關鍵字
:return:
'''
with open(File_Path) as f:
f.seek(0, 2)
cur = f.tell()
temp = 0
count = 0
text = ''
HelpInfoHead('NewKeyData', File_Path, cur)
while True:
f.seek(cur)
ch = f.readlines()
# 如果沒有讀到資料,跳出循環
if not ch:
if HelpInfoEnd('NewKeyData', temp) == 'no':
break
else:
for line in ch:
rs = re.search(KeyWord, line)
if rs:
count += 1
text += line
HelpInfoContent(text)
print('[命中{count}次]'.format(count=count))
temp += 1
cur = f.tell()
def HelpInfoHead(FuctionName, File_Path, bits = -1):
'''
提示資訊——頭部
:param FuctionName:函數名
:param file_name: 檔案名
:param bits: 目前檔案結束位址
:return:
'''
file_name = os.path.basename(File_Path)
print(FuctionName)
print('----------------------------------------------------------')
print('Start Listen The File ({file_name}) Info ...'.format(file_name=file_name))
if bits != -1:
print('The File Ends in {bits} bits . '.format(bits=bits))
print('//')
def HelpInfoEnd(FuctionName,times=-1):
'''
提示資訊——尾部
:return: no 結束 yes 繼續
'''
if times == 0:
raw = input('Wait Code (not "no") To Start Check:')
elif times == -1 :
raw = 'no'
else:
print('Check {times} times. '.format(times=times))
raw = input('Continue Check The File Key Info (yes/no):')
print('No {FuctionName} in {clock}'.format(FuctionName= FuctionName, clock = GetTime()) )
if raw == 'no' or raw == 'NO':
print('check finish !')
print('----------------------------------------------------------')
sign = 'no'
else:
sign = 'yes'
return sign
def HelpInfoContent(text, times = 0):
print('**********************************************************')
if times != 0:
print('Check {times} times. '.format(times=times))
print('Changed at {times} content: \n {text}'.format(
times=GetTime(), text=text))
# count = 1
# for line in text:
# print('{count} \t {line}'.format(count = count, line = line))
# count += 1
print('**********************************************************')
def GetTime():
'''
傳回目前時間
:return:
'''
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))