以前要修改wordpress模板上的具体内容时,总是把模板文件夹下载下来,通过sublime text打开文件夹,才能具体的查找到相关内容
当然linux通过grep也可以实现,但还是达不到自己想要的效果
于是用所学的pythoon生成器写了一个小程序
该程序能够查找文件夹下各个文件,并返回关键词所在行号、该行内容、文件所在地址
具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #!/bin/python3 # -*- coding:utf-8 -*- #modules import os,sys #functions def init(func): ''' initialization generator functions ''' def wrapper(*args,**kwargs): res = func(*args,**kwargs) next(res) return res return wrapper def get_filepath(keyword,dir_path): '''get file path''' path_list = os.walk(dir_path) file_path = ('%s/%s'%(x[0],y) for x in path_list for y in x[-1]) for x in file_path: open_file(cat_file(print_file())).send((x,keyword)) @init def open_file(target): '''open file send to cat_file''' while True: path,keyword = yield with open(path,'r') as file_read: target.send((path,keyword,file_read)) @init def cat_file(target): '''cat file content , grep by keyword,get keywork in line and send to print''' while True: count = 1 path,keyword,file_read = yield for x in file_read: if keyword in x: target.send((path,x.strip(),count)) count += 1 @init def print_file(): '''print keywork in which line\line content\file path''' while True: path,line,count = yield print("file:%s in line:\033[1;43m%s\033[0m found(%s)" %(path,count,line)) #main program def main(): if len(sys.argv) == 3: if os.path.isdir(sys.argv[2]): get_filepath(sys.argv[1],sys.argv[2]) else: print("path must directory!") else: print("find.py [keyword] [directory path]") #program entry if __name__ == '__main__': main() |