栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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_codesxxx"
  find_in_path_recursively(path, ip_port_finder)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/17577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号