ubuntu下查找脚本 写了一个查找包装。少敲点命令。 代码: ``` import subprocess, os, sys import getopt import re def cmd(cmdstr): ps = subprocess.Popen(cmdstr, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) while True: data = ps.stdout.readline() if data == b'': if ps.poll() is not None: break else: # print("libos output: {}".format(data)) yield str(data, errors='ignore') def search(search_word, search_suffix): try: cmdstr = "find {} -name \"{}\"".format(os.path.abspath("./"), search_word) results = cmd(cmdstr) for item in results: if search_suffix: suffix = os.path.splitext(item)[1][1:].lower().strip() if suffix in search_suffix: print(item, end="") else: print(item, end="") except KeyboardInterrupt: pass except Exception as errors: print(errors) def grep(search_word, search_suffix): try: cmdstr = "grep -r \"{}\" {}".format(search_word, os.path.abspath("./")) results = cmd(cmdstr) for item in results: if len(item) > 512: continue # print(item.split(":")[0]) if ":" in item: cur_path = item.split(":")[0] else: continue if search_suffix: suffix = os.path.splitext(cur_path)[1][1:].lower().strip() if suffix in search_suffix: print_color(item, search_word) else: print_color(item, search_word) except KeyboardInterrupt: pass except Exception as errors: print(errors) def print_color(main_wd, key_wd): class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' match_key_wd = re.search(key_wd, main_wd) main_wd = re.sub(key_wd, bcolors.OKBLUE + match_key_wd.group(0) + bcolors.ENDC, main_wd) print(main_wd,end="") opts, args = getopt.getopt(sys.argv[1:], "s:g") for op, value in opts: if op == "-s": no_search_suffix = value.split(",") search_word = args[0] search(search_word, no_search_suffix) if op == "-g": search_suffix = [] search_word = args[0] grep(search_word, search_suffix) if len(opts) == 0: search_suffix = [] search(args[0], search_suffix) ``` 配置: .bashrc ``` alias fcd='python3 ~/workspace/find/find.py' alias gcd='python3 ~/workspace/find/find.py -g' ``` 来自 大脸猪 写于 2017-02-23 14:34 -- 更新于2020-10-19 13:06 -- 0 条评论