12/12
02:10
IT python

grep 2.0

相对于上个版本增加了过滤目录功能,重写了整个结构.

import re
import os
import argparse

def parseInput():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", nargs='*')
    parser.add_argument('-f',nargs='*') 
    parser.add_argument('-s',nargs='*')  
    parser.add_argument('-k',nargs='*')
    args = parser.parse_args()   
    return args.p, args.f, args.s, args.k

def make_filter(plist):
    if not plist:
        return None
    def find(s):
        for eachp in plist:
            if eachp.findall(s[-1]):
                return True
        return False
    return find
            
def involve_dir(arg, dirname, names):
    # dirname   one dir
    # names     all file names in this dir
    filter_folder, filter_file, filter_key = arg
    #print dirname
    if filter_folder is None or filter_folder([dirname]):
        out_names = enumerate(names) if filter_file is None else filter(filter_file, enumerate(names))  
        for i, fname in out_names:
            file_path = os.path.join(dirname,fname)
            if filter_key is None:
                print file_path
            else:              
                try:    
                    with open(file_path) as fr:
                        lines = filter(filter_key, enumerate(fr))
                        if lines:
                            print file_path
                            for lineid, eachline in lines:
                                print "line %d: %s"%(lineid+1, eachline.rstrip('\n'))
                            print ""
                except:
                    #print "Warning cannot open file %s"%file_path
                    pass

def search(paths, args):
    for eachpath in paths:
        os.path.walk(eachpath, involve_dir, args)
            

if __name__ == "__main__":
    pattern = re.compile(r'coroutine')
    
    fpaths, ffolders, ffiles, fkeys = parseInput()
    
    if not (ffolders or ffiles or fkeys):
        print 'USAGE: -p paths -f folder_filters(should be regular expression) -s file_filters(should be regular expression) -k keys(must be regular expression)'
        quit()
    
    print "Search paths:", fpaths
    print "Folder filters", ffolders
    print "File filters:", ffiles
    print "Search keys:", fkeys
    print ""    
    
    if not fpaths:
        fpaths = [os.getcwd()]
            
    folder_pattern = []
    if ffolders:
        for eachf in ffolders:
            folder_pattern.append(re.compile(eachf, re.I))
    
    file_pattern = []
    if ffiles:
        for eachf in ffiles:
            file_pattern.append(re.compile(eachf, re.I))
        
    key_pattern = []
    if fkeys:
        for eachk in fkeys:
            key_pattern.append(re.compile(eachk, re.I))
    
    filter_folder = make_filter(folder_pattern)
    filter_file = make_filter(file_pattern)
    filter_key = make_filter(key_pattern)
    
    search(fpaths, (filter_folder, filter_file, filter_key))

发表评论