功能特性
- 遞歸遍歷指定目錄(支持符號鏈接)
- 文件名模式過濾(fnmatch)
- 文件內容全文搜索關鍵詞
- 上下文片段高亮顯示匹配行
- 統計耗時與掃描文件數
完整代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time, fnmatch
class FileSearcher:
def __init__(self, path, keyword, file_filters, context=35, max_hits=20):
self.path = path
self.keyword = keyword
self.filters = file_filters
self.context = context
self.max_hits = max_hits
def run(self):
print(f"Search '{self.keyword}' in [{self.path}]...")
print("_" * 80)
t0 = time.time()
count = self._walk()
print("_" * 80)
print(f"{count} files searched in {time.time()-t0:.2f} sec.")
def _walk(self):
cnt = 0
for root, dirs, files in os.walk(self.path, followlinks=True):
for fname in files:
if any(fnmatch.fnmatch(fname, pat) for pat in self.filters):
self._search_file(os.path.join(root, fname))
cnt += 1
return cnt
def _search_file(self, filepath):
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
except Exception:
return
if self.keyword in content:
print(filepath)
self._print_context(content)
def _print_context(self, content):
pos = 0
kw_len = len(self.keyword)
for _ in range(self.max_hits):
idx = content.find(self.keyword, pos)
if idx == -1: break
start = max(0, idx - self.context)
end = min(len(content), idx + kw_len + self.context)
snippet = content[start:end].replace('\n', ' ').replace('\r', '')
print(f" >>> {snippet}")
pos = idx + kw_len
print()
if __name__ == '__main__':
FileSearcher(
path=r"C:\projects",
keyword="TODO",
file_filters=("*.py", "*.js", "*.md"),
context=40,
max_hits=10
).run()
關鍵點
errors='ignore' 跳過編碼錯誤,適用於混合編碼項目。
followlinks=True 遍歷符號鏈接,需防止循環鏈接導致無限遞歸。
- 上下文片段去除換行符,單行顯示便於閱讀。