Python基于gevent實現(xiàn)文件字符串查找器
1、遞歸遍歷目錄下所有文件并通過finder函數(shù)定位指定格式字符串
2、用來查找字符串的finder函數(shù)是自己定義的,這里定義了一個ip_port_finder通過正則表達式查找ip:port格式(粗匹配:數(shù)字.數(shù)字.數(shù)字.數(shù)字:數(shù)字)的字符串
3、用gevent來實現(xiàn)協(xié)程并發(fā)完成耗時任務
代碼如下:
# -*- coding: utf-8 -*- import re from os.path import join from os import walk from gevent import monkey import gevent monkey.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)目標:{matchObj.group(0)}") return True else: return False def 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_codes\xxx" find_in_path_recursively(path, ip_port_finder)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python RuntimeError: thread.__init__() not called解決方法
這篇文章主要介紹了Python RuntimeError: thread.__init__() not called解決方法,需要的朋友可以參考下2015-04-04Python+OpenCV實現(xiàn)邊緣檢測與角點檢測詳解
這篇文章主要為大家詳細介紹了如何通過Python+OpenCV實現(xiàn)邊緣檢測與角點檢測,文中的示例代碼講解詳細,對我們學習Python與OpenCV有一定的幫助,需要的可以參考一下2023-02-02詳解python讀取matlab數(shù)據(jù)(.mat文件)
本文主要介紹了python讀取matlab數(shù)據(jù),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12教你使用Python建立任意層數(shù)的深度神經(jīng)網(wǎng)絡
這篇文章主要介紹了Python建立任意層數(shù)的深度神經(jīng)網(wǎng)絡,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08