Как улучшить этот хвостоподобный код Python - PullRequest
1 голос
/ 12 мая 2011

Я просто хочу знать, есть ли у вас, ребята, лучшие способы сделать это, чем тот, который я придумал.Я хочу создать скрипт, похожий на tail -f, который будет активно искать строку и печатать только текст, связанный с этой строкой, в режиме реального времени.Как вы можете видеть из кода, я ищу MAC-адреса, но я думаю, что он может быть использован для некоторых других целей.

Я думал, что должен быть лучший способ сделать это.Возможно, один из вас, ребята, знает умный алгоритм или команду, которая делает это лучше.Спасибо за вашу помощь

import time, os, sys
from datetime import date

# Function to get the file size, it will help us go to the end of a file
def current_file_size(filename):
    file_results = os.stat(filename)
    file_size = file_results[6]
    return file_size

# Check for correct usage
if len(sys.argv) != 2:
    print "Usage: %s <mac_address>" % sys.argv[0]
    sys.exit()

#Get the date in the format that the log uses
now = date.today()
todays_date = now.strftime("%Y%m%d")

#Set the filename and open the file
filename = 'complete.log'
file = open(filename,'r')

#Find the size of the file and move to the end
st_size = current_file_size(filename)
file.seek(st_size)

while 1:
    where = file.tell()   # current position of the file
    time.sleep(2)         # sleep for a little while
    st_size = current_file_size(filename)
    if st_size > where:       # if there's new text
        alotoflines = file.read(st_size-where)    # get the new lines as a group
        # search for the tag+mac address
        found_string = alotoflines.find("<mac v=\"" + sys.argv[1])
        if found_string > 0:
            # search for the immediately prior date instance from where the MAC address
            # is. I know that the log entry starts there
            found_date_tag = alotoflines.rfind(todays_date,0,found_string)
            print alotoflines[found_date_tag:]

1 Ответ

1 голос
/ 12 мая 2011

Вы делаете это как упражнение Python или можете использовать оболочку?

Вы можете просто передать вывод хвоста в grep?

tail -F myfile.txt | egrep --line-buffered myPattern

Вы можете поместить это в скрипт и создать аргументы файла и шаблона.

Используя grep, вы также можете добавить контекст к своему выводу, используя ключи -A и -B.

...