2011-05-12 82 views
1

我只想知道,如果你們有更好的方式來做到這一點,比我想出的方式。我想要的是製作一個「尾巴-f」式的腳本,但它會主動查找字符串並實時打印與該字符串相關的文本。正如你從代碼中看到的,我正在尋找MAC地址,但我想它可以用於其他一些目的。如何改進這種類似於尾巴的Python代碼

我在想這樣做一定有更好的方法。也許你們中的一個人知道一個聰明的算法或者一個能夠做得更好的命令。感謝您的幫助

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:] 
+0

更改'如果st_size>其中:'變量'where'因爲這實際上是一個python builtin。 – 2011-05-12 11:46:49

+1

您也可以將文檔字符串添加到您的功能而不是註釋。記住Doc字符串解釋它的作用,評論解釋如何。 – 2011-05-12 11:56:45

+1

您是否檢查過在此提出的解決方案? http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail – 2011-05-12 16:11:37

回答

1

您是在做這個Python練習還是可以使用shell?

你可以簡單地將尾部輸出管道化爲grep嗎?

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

你可以把這個變成一個腳本,使文件和模式ARGS。

使用grep,您還可以使用-A和-B開關將上下文添加到輸出。

+0

我不知道模式匹配之前或之後需要輸出多少行,所以我不知道把什麼放在-A和-B開關上 – perrocontodo 2011-05-12 12:10:34