Python基于gevent實(shí)現(xiàn)文件字符串查找器
1、遞歸遍歷目錄下所有文件并通過finder函數(shù)定位指定格式字符串
2、用來查找字符串的finder函數(shù)是自己定義的,這里定義了一個ip_port_finder通過正則表達(dá)式查找ip:port格式(粗匹配:數(shù)字.數(shù)字.數(shù)字.數(shù)字:數(shù)字)的字符串
3、用gevent來實(shí)現(xiàn)協(xié)程并發(fā)完成耗時任務(wù)
代碼如下:
# -*- 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'發(fā)現(xiàn)目標(biāo):{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'所在行數(shù):{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)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解盒子端CSS動畫性能提升2. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案3. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法4. ASP實(shí)現(xiàn)加法驗(yàn)證碼5. 阿里前端開發(fā)中的規(guī)范要求6. PHP設(shè)計(jì)模式中工廠模式深入詳解7. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)8. ASP基礎(chǔ)知識Command對象講解9. ASP中格式化時間短日期補(bǔ)0變兩位長日期的方法10. PHP循環(huán)與分支知識點(diǎn)梳理
