Python基于gevent實(shí)現(xiàn)文件字符串查找器
1、遞歸遍歷目錄下所有文件并通過(guò)finder函數(shù)定位指定格式字符串
2、用來(lái)查找字符串的finder函數(shù)是自己定義的,這里定義了一個(gè)ip_port_finder通過(guò)正則表達(dá)式查找ip:port格式(粗匹配:數(shù)字.數(shù)字.數(shù)字.數(shù)字:數(shù)字)的字符串
3、用gevent來(lái)實(shí)現(xiàn)協(xié)程并發(fā)完成耗時(shí)任務(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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考2. 淺談django不使用restframework自定義接口與使用的區(qū)別3. 如何理解SpringMVC4. 關(guān)于PHP程序員解決問(wèn)題的能力5. 解決idea web項(xiàng)目中out目錄更新不同步問(wèn)題6. 淺談在django中使用redirect重定向數(shù)據(jù)傳輸?shù)膯?wèn)題7. Spring Bean管理注解方式代碼實(shí)例8. 跟我學(xué)XSL(二)第1/4頁(yè)9. 解決IDEA2020控制臺(tái)亂碼的方法10. 關(guān)于Spring自定義XML schema 擴(kuò)展的問(wèn)題(Spring面試高頻題)
