如何改进这种类似尾部的Python代码

时间:2011-05-12 09:59:54

标签: python optimization tail

我只是想知道你们有没有比我想出的更好的方法。我想要的是制作一个类似“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 个答案:

答案 0 :(得分:1)

您是在进行Python练习还是使用shell?

你能简单地将尾部输出管道输入grep吗?

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

您可以将其放入脚本中并制作文件和模式args。

使用grep,您还可以使用-A和-B开关为输出添加上下文。