mqzlp 发表于 2018-8-8 11:10:26

《可爱的Python》读书笔记(九)

# -*- coding: utf-8 -*-  
import os
  
import time
  
from threading import Thread
  
from configparser import RawConfigParser as rcp
  

  

  
class grepIt(Thread):
  

  
    def __init__(self, cdcfile, keyword):
  

  
      Thread.__init__(self)
  
      self.cdcf = cdcfile
  
      self.keyw = keyword.upper()
  
      self.report = ""
  
    def run(self):
  

  
      if self.cdcf.endswith('.ini'):
  
            self.report = marklni(self.cdcf, self.keyw)
  

  

  
def marklni(cdcfile, keyword):
  
    """配置文件模式匹配函数
  
    """
  
    report = ""
  
    keyw = keyword.upper()
  
    cfg = rcp()
  
    cfg.read(cdcfile)
  
    nodelist = cfg.sections()
  
    nodelist.remove("Comment")
  
    nodelist.remove("Info")
  
    for node in nodelist:
  
      if keyw in node.upper():
  
            print(node)
  
            report += "\n %s" % node
  
            continue
  
      else:
  
            for item in cfg.items(node):
  
                if keyw in item.upper():
  
                  report += "\n %s\%s" % (node, item)
  
    return report
  

  
def grepSearch(cdcpath, keyword):
  
    """多线程群体搜索函数
  
    """
  
    begin = time.time()
  
    filelist = os.listdir(cdcpath)
  
    # 用于记录发起的搜索线程
  
    searchlist = []
  
    for cdcf in filelist:
  
      pathcdcf = "%s\%s" % (cdcpath, cdcf)
  
      #print(pathcdcf)
  
      # 初始化线程对象
  
      current = grepIt(pathcdcf, keyword)
  
      # 追加记录线程队列
  
      searchlist.append(current)
  
      # 发动线程处理
  
      current.start()
  
    for searcher in searchlist:
  
      searcher.join()
  
      print("Search from", searcher.cdcf, "out", searcher.report)
  
    print("usage %s s" % (time.time() - begin))
  

  

  
if __name__ == "__main__":
  

  
    grepSearch("F:\\back", "images")
页: [1]
查看完整版本: 《可爱的Python》读书笔记(九)