下面的python 2.5腳本可以工作,但由於我是初學者,我不知道是否存在任何明顯的錯誤或者更好的方法來實現我想實現的目標?從日誌文件和電子郵件結果中提取新錯誤
目標是打開當天的日誌 - '/ Library/Application Support/Perceptive Automation/Indigo 5/Logs /',並提取包含單詞錯誤的行並僅發送新錯誤。 提取錯誤行後,在tmp.txt
中計數行數(prenumLines
)。然後將提取的行寫入tmp.txt
文件,並再次對行 進行計數(postnumLines
)。大於prenumLines
的行號被打印到'theBody'並通過電子郵件發送。
from datetime import date
import linecache
fileDate = str(date.today())
theBody = []
tmpFile = open('/Library/Application Support/Perceptive Automation/Indigo 5/Logs/tmp.txt')
prenumLines = sum(1 for line in tmpFile)
log= open('/Library/Application Support/Perceptive Automation/Indigo 5/Logs/' + fileDate + ' Events.txt', 'r')
tmpFile = open('/Library/Application Support/Perceptive Automation/Indigo 5/Logs/tmp.txt', 'w')
for line in log:
if 'Error' in line:
tmpFile.write(line)
log.close()
tmpFile.close()
postnumLines = sum(1 for line in open('/Library/Application Support/Perceptive Automation/Indigo 5/Logs/tmp.txt'))
lineNum = prenumLines
while lineNum < postnumLines:
theBody.append(linecache.getline('/Library/Application Support/Perceptive Automation/Indigo 5/Logs/tmp.txt', lineNum + 1))
lineNum = lineNum + 1
tmpFile.close()
theBody = "".join(theBody)
#theBody is the body of an email which is sent next
#print theBody
非常感謝您的詳細回覆。我目前正在通過它來試圖瞭解您的意見和更改。我不知道它是否會改變您的某些回覆,但我想要做的是將該身體作爲電子郵件發送,但僅適用於自上一封電子郵件以來發生的任何新錯誤。包含錯誤的日誌以當前日期命名約會它只是當前的日誌,我想從中獲取錯誤。再次感謝! – 2013-03-24 21:26:41
我試着用一行'tmp.txt'測試你的原始腳本,並在每日日誌中做了5行中的3行。 'tmp.txt'沒有被追加,而是被覆蓋。你沒有看到這種行爲嗎?如果在經過這個之後有任何問題,請讓我知道。 – Anthon 2013-03-25 04:33:18
生成日誌的軟件是Indigo,一個自動化程序。它每天寫入一個新日誌。我設置了腳本,每10分鐘解析一次日誌,查找錯誤併發送郵件。我想要新的新錯誤,而不是以前發送的錯誤。我在tmp.text中統計了這些行,並添加了新的錯誤,以前寫入的任何錯誤都被覆蓋。因此,如果tmp.txt中有5行,並且添加了3行,則只會發送3行新行。我做了一些你所建議的修改,但是我發現我不能在軟件中使用包含'with statements'的腳本。再次感謝你的幫助。 – 2013-03-26 12:56:42