1. 程式人生 > >Python3在指定路徑下遞歸定位文件中出現的字符串

Python3在指定路徑下遞歸定位文件中出現的字符串

裝飾器 post sea 搜索 ima all entry syntax sys

[本文出自天外歸雲的博客園]

腳本功能:在指定的路徑下遞歸搜索,找出指定字符串在文件中出現的位置(行信息)。

用到的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])

本地運行腳本,搜索結果示例如下:

技術分享圖片

Python3在指定路徑下遞歸定位文件中出現的字符串