Python3在指定路径下递归定位文件中出现的字符串

[本文出自天外归云的博客园]

脚本功能:在指定的路径下递归搜索,找出指定字符串在文件中出现的位置(行信息)。

用到的python特性:

1. PEP 318 -- Decorators for Functions and Methods

2. PEP 380 -- Syntax for Delegating to a Subgenerator

3. PEP 471 -- os.scandir() function -- a better and faster directory iterator

4. PEP 498 -- Literal String Interpolation

代码如下:

import os
import sys

__all__ = ['DirPath']

'''
    在指定路径下递归查找包含指定字符串的文件
    可以指定查找的文件类型category-默认为'.py'
    可以指定查找的字符串str-默认为'python'
'''


class DirPath(object):
    # 初始化参数查找路径-path
    def __init__(self, path):
        self.show = self.show()
        self.path = path

    # 开启func协程的装饰器
    def on(func):
        def wrapper(*args):
            res = func(*args)
            next(res)
            return res

        return wrapper

    @on
    # 搜索path路径下的python文件
    def search(self, target, category):
        while True:
            path = yield
            for entry in os.scandir(path):
                if entry.is_file():
                    if entry.name.endswith(category):
                        target.send(entry.path)
                if entry.is_dir():
                    self.search(target, category).send(entry.path)

    @on
    # 找到f文件中包含str的行信息并发送给target
    def find_str(self, target, str):
        while True:
            path = yield
            with open(path, "r", encoding='utf-8') as f:
                for (name, value) in enumerate(f):
                    if str in value:
                        target.send(f"[{path}][{name+1}]:{value}")

    @on
    # 展示查询结果
    def show(self):
        while True:
            res = yield
            print(res)

    # 默认在'.py'类型文件中查找字符串-可以指定文件类型category
    # 默认查找字符串'python'-可以指定查找字符串str
    def code_search(self, category=".py", str="python"):
        self.search(self.find_str(self.show, str), category).send(self.path)


if __name__ == '__main__':
    path = sys.argv[1]
    Dir = DirPath(path)
    Dir.code_search(str=sys.argv[2], category=sys.argv[3])

本地运行脚本,搜索结果示例如下:

posted @ 2018-03-29 13:30  天外归云  阅读(851)  评论(0编辑  收藏  举报