欢迎来到代码驿站!

当前位置:首页 >

Python基于gevent实现文件字符串查找器

时间:2020-08-11 12:00:05|栏目:|点击:

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)

上一篇:详解MySQL分区表

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:Python基于gevent实现文件字符串查找器

本文地址:http://www.codeinn.net/misctech/3378.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有