Python基于gevent實現文件字符串查找器
1、遞歸遍歷目錄下所有文件并通過finder函數定位指定格式字符串
2、用來查找字符串的finder函數是自己定義的,這里定義了一個ip_port_finder通過正則表達式查找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_codesxxx' find_in_path_recursively(path, ip_port_finder)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: