乌拉、利用python实现tree命令
生活随笔
收集整理的這篇文章主要介紹了
乌拉、利用python实现tree命令
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
由于服務(wù)器中沒(méi)有tree命令,且自己沒(méi)有權(quán)限install新命令,只能自個(gè)用python實(shí)現(xiàn)該命令,費(fèi)勁
具體實(shí)現(xiàn)方法如下
以下操作基于Linux,python2
1. 首先就是隨便選個(gè)位置,然后新建個(gè)py文件(這里選在了"~/.basic_scipt",命名為"tree.py",可參考)。py文件內(nèi)容如下:
#!/usr/bin/python2 # coding:utf-8 import os import sys# -d 只顯示目錄 # -a 顯示所有目錄 # -L num 顯示幾層,不顯示隱藏文件def print_color(color,argv):if color == "green":print("\033[32m"+argv+"\033[0m")elif color == "read":print("\033[31m"+argv+"\033[0m")elif color == "yellow":print("\033[33m"+argv+"\033[0m")else :print(argv)def is_hidden(file):file_name = os.path.basename(file)if file_name[0] == '.':return Trueelse:return Falsedef get_len_of_listdir(lst,show_hidden=True):len_of_listdir = 0for file in lst:if show_hidden == True:len_of_listdir += 1elif is_hidden(file) is not True:len_of_listdir += 1return len_of_listdirdef tree_dir(dir, show_hidden_file, direct_only, layer_limit, layer_max,layer=0):layer_max = int(layer_max)files = os.listdir(dir)files.sort()file_lst=[]dir_lst=[]for file in files:file_path = os.path.join(dir, file)if os.path.isdir(file_path):dir_lst.append(file)else:file_lst.append(file)if show_hidden_file == False:len_of_listdir = get_len_of_listdir(dir_lst)len_of_listfile = get_len_of_listdir(file_lst)else:len_of_listdir = get_len_of_listdir(dir_lst,show_hidden=False)len_of_listfile = get_len_of_listdir(file_lst,show_hidden=False)if direct_only is not True:index = 0for file in file_lst:file_path = os.path.join(dir, file) if layer_limit == True and layer >= layer_max:continueif show_hidden_file == False and is_hidden(file) is True:continue index += 1print(" | " * (layer)),if (layer >= 0):if index == len_of_listfile and len_of_listdir == 0:print("|__ "),else:print("|__ "),print(file)index = 0for file in dir_lst:file_path = os.path.join(dir, file) if layer_limit == True and layer >= layer_max:continueif show_hidden_file == False and is_hidden(file) is True:continue index += 1print(" | " * (layer)),if (layer >= 0):if index == len_of_listdir:print("|__ "),else:print("|__ "),print_color("green", file)tree_dir(file_path, show_hidden_file, direct_only, layer_limit, layer_max,layer + 1)def parse_option(op_str):print("option:" + op_str)import relayer_limit = Falselayer_max = 0direct_only = Falseshow_hidden_file = Falsematch_str = format("-L[\s]+\d")search_ret = re.search(match_str, op_str)if search_ret is not None:layer_limit = Truematch_str = format("\d")search_ret = re.search(match_str, search_ret.group(0))if search_ret is not None:layer_max = search_ret.group(0)match_str = format("-a")search_ret = re.search(match_str, op_str)if search_ret is not None:show_hidden_file = Truematch_str = format("-d")search_ret = re.search(match_str, op_str)if search_ret is not None:direct_only = Truereturn show_hidden_file, direct_only, layer_limit, layer_maxif __name__ == '__main__':file_name = sys.argv[0]if len(sys.argv) < 2:print_color("red", "args invalid\n")sys.exit(1)path_dir = sys.argv[1]op = ""for idx in range(len(sys.argv)):if idx >= 2:op += " " + sys.argv[idx]show_hidden_file, direct_only, layer_limit, layer_max = parse_option(op)tree_dir(path_dir,show_hidden_file, direct_only, layer_limit, layer_max)sys.exit(0)2. 功能選項(xiàng)如下所示,詳見(jiàn)第五條內(nèi)容中的代碼部分
# -d 只顯示目錄 # -a 顯示所有目錄 # -L num 顯示幾層,不顯示隱藏文件3. 找到home目錄下的".bashrc"文件(或".cshrc"文件,均為隱藏文件。這里用的是bashrc文件)。進(jìn)入文件后編輯,隨意找個(gè)位置添加一行alias指令,內(nèi)容如下:
alias tree='python ~/.basic_scipt/tree.py ./'如果沒(méi)有找到".bashrc"文件,修改".cshrc"文件亦可,命令如下(bashrc和cshrc修改一個(gè)即可):
alias tree 'python ~/.basic_scipt/tree.py ./' #注意沒(méi)有等號(hào)=4.完成以上操作之后,記得保存并退出。然后在命令終端執(zhí)行如下指令(source),以使bashrc文件(或cshrc文件)的更改生效:
$ source ~/.bashrc # 或 $ source ~/.cshrc5. 在source命令執(zhí)行完之后,就已經(jīng)大功告成了,趕緊找個(gè)目錄tree一下試試吧。如果報(bào)錯(cuò)的話,就看看python代碼部分有沒(méi)有錯(cuò)誤吧。
$ tree #沒(méi)錯(cuò)就這么簡(jiǎn)單,但還可以加一些參數(shù),如下 $ tree -L 2 #顯示兩層文件,避免眼花繚亂 $ tree -d #只顯示目錄6. 需要注意的是,該代碼是使用的python2平臺(tái),如是python3平臺(tái)的話,估計(jì) 肯定會(huì)出現(xiàn)不兼容,然后報(bào)錯(cuò)。
7. 需要注意的第二點(diǎn),由于對(duì)該命令作了些簡(jiǎn)化,所以只能實(shí)現(xiàn)對(duì)當(dāng)前所在路徑的tree,即加一些路徑當(dāng)作參數(shù)是不可以的。例:
$ tree ../ #這是錯(cuò)誤的用法python代碼參考了其他人的博客,略微做了些修改,忘記出處了,見(jiàn)諒
如果您在實(shí)際使用中出現(xiàn)問(wèn)題或者有更好的解決辦法,歡迎留言。
總結(jié)
以上是生活随笔為你收集整理的乌拉、利用python实现tree命令的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Windows 中使用苹果 macOS
- 下一篇: 图解矩阵的秩