這只是希望提高我的編程技能。該劇本適用於我想要做的事情,我只想知道是否有更好的或更有利的做法。 2天后,如果我唯一的迴應是「這是應該如何做」,我會接受這個最好的答案。但我對此表示懷疑。這也是第一次在Linux中編寫腳本,所以很有趣。寫一個文件中多個文件中出現多個文件並將結果寫入另一個文件的最佳方式是什麼?
我們有一堆保存在主目錄的不同子目錄中的日誌文件。我們希望編寫一個腳本,查看所有日誌文件中的單詞「錯誤」和/或「異常」,併爲每個文件增加一個計數器。它會將所有結果寫入1個錯誤文件和1個異常文件。所以,最終文件應該是這樣的:
Errors:
dir/subdir1/log1.log: 23
dir/subdir2/log2.log: 2
dir/subdir2/log3.log: 194
dir/subdir3/log4.log: 1
同樣適用於例外。這基本上讓我們知道大部分故障發生在哪裏。下面是我寫的做到這一點的代碼:
# set today's date and the directory that will be searched through recursively (1)
date - datetime.now().strftime("%Y-%m-%d")
dir = "directory/of/main/folder"
# set file names containing today's date (2)
errors_file = "%s/%s_LogErrors.txt" % (dir, date)
exceptions_file = "%s/%s_LogExceptions.txt" % (dir, date)
# create 2 text files containing the name of each log file matched with the corresponding number of errors or exceptions (3)
os.system("cat * | grep -r -i -c 'Error' '%s' > '%s'" % (dir, errors_file))
os.system("cat * | grep -r -i -c 'Exception' '%s' > '%s'" % (dir, exceptions_file))
# open the errors file and set the contents of the file to error_content (4)
error_file = open(os.path.join(dir, errors_file), 'r')
error_content = error_file.readlines()
error_file.close()
# write a header to the errors file (5)
error_file = open(errors_file, 'w')
error_file.write("-"*120 + "\n")
error_file.write("These are the errors from all the log files. The number on the right is the number of "
"errors in the corresponding file.\n")
error_file.write("-"*120 + "\n")
# remove lines that have 0 errors and add a space between the colon and the number of errors (6)
for line in error_content:
if line.strip().endswith(":0"):
continue
else:
error_file.write(line.replace(":", ": ") + "\n")
error_file.close()
# open the exceptions file and set the contents of the file to exception_content (7)
exception_file = open(exceptions_file, 'r')
exception_content = exception_file.readlines()
exception_file.close()
# write a header to the exceptions file (8)
exception_file = open(exceptions_file, 'w')
exception_file.write("-"*128 + "\n")
exception_file.write("These are the exceptions from all the log files. The number on the right is the number "
"of exceptions in the corresponding file.\n")
exception_file.write("-"*128 + "\n")
# remove lines that have 0 exceptions and add a space between the colon and the number of exceptions (9)
for line in exception_content:
if line.strip().endswith(":0"):
continue
else:
exception_file.write(line.replace(":", ": ") + "\n")
exception_file.close()
我增加了一些每個塊的註釋,使其更容易爲你們引用一個特定的代碼段。它看起來像我寫了更多的代碼,但我不知道會發生什麼變化。
在此先感謝!