zoukankan      html  css  js  c++  java
  • 面向过程---通过查找字符串,找到相应的文件路径

    命令 grep  -rl  'python'  路径  :在一个目录下面找到含有字符串 python 内容的文件

    通过一个命令来实现查找字符串的效果

     一装饰器:给生成器一个初始化

    def init(func):
        def inner(*args,**kwargs):
            res=func(*args,**kwargs)
            next(res) #装饰器初始化一次
            return res
        return inner

    二 拿到文件下所有文件的绝对路径

    @init
    def search(target):
        while True:
            filepath=yield
            g = os.walk(filepath)  # 生成器
            for pardir,_,files in g:
                for file in files:
                    abs_path=r'%s\%s'%(pardir,file)
                    target.send(abs_path)

    三 打开文件拿到文件对象

    @init
    def opener(target):
        while True:
            abs_path=yield
            # print('opener func--->',abs_path)
            with open(abs_path,'rb') as f:
                #把 abs_path,f 传给下一个阶段
                target.send((abs_path,f))

    四 读取文件的每行内容

    @init
    def cat(target):
        while True:
           abs_path, f=yield
           for line in f:
               res=target.send((abs_path,line))
               if res:
                   break

    五判断字符是否在里面

    @init
    def grep(target,pattern):
        pattern = pattern.encode('utf-8')
        res=False #作用:变量要用的话先定义
        while True: #一直循环前面文件传过来的值
            abs_path,line=yield res #yield后面是传的值
            res=False #保证判断之前res都为False
            if pattern in line:
                res=True #改变了res的值
                target.send(abs_path)

    六打印最终的文件路径

    @init
    def printer():
        while True:
            abs_path=yield
            print('<%s>'%abs_path)
    
    g=search(opener(cat(grep(printer(),'python'))))
    g.send(r'G:studyday09a')

    七执行需要的查找命令

    g=search(opener(cat(grep(printer(),'python'))))
    g.send(r'G:studyday09a')
  • 相关阅读:
    pytest
    pytest 跳过测试用例 skip
    pytest
    pytest -allure标记用例级别severity
    pytest-
    pytest-分布式执行(pytest-xdist)
    4、win10搭建easy-mock平台
    pandas日期缺失,空值填充方法
    Pandas拼接操作(concat,merge,join和append)的区别
    关于docker容器和镜像的区别
  • 原文地址:https://www.cnblogs.com/mmyy-blog/p/9298555.html
Copyright © 2011-2022 走看看