標籤:def 部落格 數字 blank 一個 imp odi tor http
[本文出自天外歸雲的部落格園]
1、遞迴遍曆目錄下所有檔案並通過finder函數定位指定格式字串
2、用來尋找字串的finder函數是自己定義的,這裡定義了一個ip_port_finder通過Regex尋找ip:port格式(粗匹配:數字.數字.數字.數字:數字)的字串
3、用gevent來實現協程並發完成耗時任務
代碼如下:
# -*- coding: utf-8 -*-import refrom os.path import joinfrom os import walkfrom gevent import monkeyimport geventmonkey.patch_all()def ip_port_finder(str: str) -> bool: pattern = re.compile(r".+\d+\.\d+\.\d+\.\d+:\d+") matchObj = pattern.match(str) if matchObj: print("------") print(f"發現目標:{matchObj.group(0)}") return True else: return Falsedef find_in_file(file_path, finder): with open(file_path, "r", encoding="utf-8", errors=‘ignore‘) as f: for (num, value) in enumerate(f): if finder(value): print(f"檔案路徑:{file_path}") print(f"所在行數:{num}")find_in_path_recursively = lambda path, finder: gevent.joinall( [gevent.spawn(find_in_file, join(root, file_name), finder) for root, directories, f_names in walk(path) for file_name in f_names])if __name__ == ‘__main__‘: path = "E:\dev_codes\xxx" find_in_path_recursively(path, ip_port_finder)
參考文章:
Python多任務實現之協程並發下載多圖片
Python3用gevent寫個檔案字串尋找器