用python编写一个高效搜索代码工具

用python编写一个高效搜索代码工具
大多码农在linux环境下使用grep+关键词的命令搜索自己想要的代码或者log文件。今天介绍用python如何编写一个更强大的搜索工具,windows下也适用。
我们的需求:
1, 可以同时指定多个关键词。比如某个文件某一行中有”error: aa bb cc”,如果检索关键词error和cc则可以显示该行,避免单一关键词冗余信息太多
2, 可以排除某些关键词。对于”error: aa bb cc” ,如果设定排除bb,则不予显示该行
3, 可以指定某些文件名或者文件名后缀,如只搜索 .cpp和 .h 的文件
4, 可以排除某些文件名或者后缀,比如排除 .log 和 .bak
5, 最重要一点,和grep一样,必须能够递归查找,只要指定一个目录,则自动逐层搜索该目录下所有的子文件夹,文件
6, 最后能打印出吻合的文件完整路径,能显示搜索到的行号

为了实现以上功能,我们需要用到python自带的os库函数,功能强大,先把用到的几个先做简单说明:
os.path.exists ( xxx ) 判断路径xxx是否存在
os.listdir ( xxx ) 把xxx路径下所有文件和文件夹名字转换成一个list列表
os.path.join ( aaa, bbb ) 把字符串aaa和bbb拼接成一个完整的文件绝对路径
os.path.isfile (xxx) 判断xxx是不是一个文件
os.path.isdir (xxx) 判断xxx是不是一个文件夹

以下是代码正文

-- coding: cp936 --

#代码准备工作
#由于需要获得文件的路径,所以要加载 os和system库
import os
import sys

#设定两个检索关键词keyword error和cc
keyword1 = ‘error‘
keyword2 = ‘cc‘

#设定一个排除的exclude_word bb
exclude_word = ‘bb‘

#设定一组指定的文件名,使用list结构以便动态扩展
file_name_list = [ ‘.sv‘, ‘.v‘, ‘.cpp‘, ‘.h‘]

#设定不参与检索的文件名,也使用list结构
exclude_file_name_list = [ ‘.bak ‘ ]

#指定一个search_path路径,把字符串留空,只初始化,为了实现在konsole界面实时捕捉当前路径
search_path = ‘ ‘

#准备工作完毕

#下面创建一个my_search函数,目的是为了实现递归查找子文件夹
#如果只需要查找当前目录层次的文件,则可以不使用函数
#传入参数为当前路径,为了实现递归查找子文件夹
def my_search ( search_path ):

#防错机制,判断当前路径是否存在
if  os.path.exists( search_path ) :

    #获得路径下所有文件文件夹的名字,并for循环遍历
    for  my_filename  in  os.listdir ( search_path ):

        #把当前路径和文件名拼接成完整绝对路径
        full_filepath = os.path.join ( search_path,  my_filename )

        #判断拼接出的完整路径是文件还是文件夹
        if os.path.isfile (full_filepath):

            #如果是文件,则对file_name_list中期望的文件名进行遍历
            for my_extend in file_name_list :

                #判断.cpp .sv等在文件名中
                if my_extend in my_filename :
                    flag = True

                    #对exclude_file_name_list中不希望的文件名进行遍历
                    for my_exclude in exclude_file_name_list :
                        #若文件名有.bak就剔除
                        if my_exclude in my_filename:
                            flag =  False

                    if flag: #文件名匹配已经命中
                        i = 0 #i作为文件行号

                        #逐行读取文件,碰到特大文件就不会卡死程序
                        for line in open ( full_filepath ) :
                            i=i+1 #每次读一行,i+1

                            #判断关键字1和2(error, cc)在该行中,并且exclude_word(bb)不在该行
                            if (keyword1 in line) and (keyword2 in line) and (exclude_word not in line):

                                #满足检索条件,打印文件完整路径,行号
                                print full_filepath , ‘line‘,i,‘:‘
                                print line #打印该行

        #当前完整路径不是文件,而是文件夹
        if os.path.isdir (full_filepath) :

            #执行函数递归,继续到下一层文件夹目录查找,直到底层文件
            my_search(full_filepath)  

else : #防错机制,当前路径不存在,则报错
    print search_path, ‘path not exist!‘

#这里相当于C语言主函数,程序从这里开始执行

search_path = os.getcwd () #从konsole获得当前路径,设为搜索路径
print search_path
my_search (search_path) #调用函数开始搜索

原文地址:http://blog.51cto.com/14075497/2343362

时间: 2024-07-30 20:28:05

用python编写一个高效搜索代码工具的相关文章

【转载】90行python搭一个音乐搜索工具 —— Song Finder

90行python搭一个音乐搜索工具 —— Song Finder Jul 23, 20153 minute read 之前一段时间读到了这篇博客,其中描述了作者如何用java实现国外著名音乐搜索工具shazam的基本功能.其中所提到的文章又将我引向了关于shazam的一篇论文及另外一篇博客.读完之后发现其中的原理并不十分复杂,但是方法对噪音的健壮性却非常好,出于好奇决定自己用python自己实现了一个简单的音乐搜索工具—— Song Finder, 它的核心功能被封装在 SFEngine 中,

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(六)

无书面许可请勿转载 高级playbook Finding files with variables All modules can take variables as part of their arguments by dereferencing them with {{ and }} . You can use this to load a particular file based on a variable. For example, you might want to select a

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(十二)

如无书面授权,请勿转载 第五章 自定义模块 External inventories In the first chapter we saw how Ansible needs an inventory file, so that it knows where its hosts are and how to access them. Ansible also allows you to specify a script that allows you to fetch the inventor

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(九)

如无书面授权,请勿转载 第四章 大型项目中Ansible的使用 New features in 1.3 There are two features in Ansible 1.3 that were alluded to previously in the chapter. The first feature is the metadata roles. They allow you to specify that your role depends on other roles. For ex

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(十)

无书面许可,请勿转载 Custom Modules Until now we have been working solely with the tools provided to us by Ansible. This does afford us a lot of power, and make many things possible. However, if you have something particularly complex or if you find yourself u

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(十一)

无书面授权,请勿转载 第五章 自定义模块 Using a module Now that we have written our very first module for Ansible, we should give it a go in a playbook. Ansible looks at several places for its modules: first it looks at the place specified in the library key in its con

[email protected]一个高效的配置管理工具--Ansible configure management--翻译(四)

无书面许可请勿转载 由于第三章内容较长,我将分做几个部分来翻译. Advanced Playbooks So far the playbooks that we have looked at are simple and just run a number of modules in order. Ansible allows much more control over the execution of your playbook. Using the following techniques

Ansi[email protected]一个高效的配置管理工具--Ansible configure management--翻译(五)

无书面许可请勿转载 高级Playbook Extra variables You may have seen in our template example in the previous chapter that we used a variable called group_names . This is one of the magic variables that are provided by Ansible itself. At the time of writing there a

使用Python编写一个渗透测试探测器

本篇将会涉及: 资源探测 一个有用的字典资源 第一个暴力探测器 资源探测 资源探测在渗透测试中还是属于资源的映射和信息的收集阶段. 主要有以下三个类型: 字典攻击 暴力破解 模糊测试 字典攻击,在破解密码或密钥的时候,通过自定义的字典文件,有针对性地尝试字典文件内所有的字典组合. 暴力破解,也叫做穷举法,按照特定的组合,进行枚举所有的组合.简单来说就是将密码进行逐个推算直到找出真正的密码为止. 模糊测试,指通过向目标系统提供非预期性的输入并监视其发生的异常结果来发现目标系统的漏洞. 资源探测的作