1. 程式人生 > 程式設計 >Python基於gevent實現檔案字串查詢器

Python基於gevent實現檔案字串查詢器

1、遞迴遍歷目錄下所有檔案並通過finder函式定位指定格式字串

2、用來查詢字串的finder函式是自己定義的,這裡定義了一個ip_port_finder通過正則表示式查詢ip:port格式(粗匹配:數字.數字.數字.數字:數字)的字串

3、用gevent來實現協程併發完成耗時任務

程式碼如下:

# -*- 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"發現目標:{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"所在行數:{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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。