結(jié)合13日和19日更的《python實(shí)現(xiàn)windows下的ls函數(shù)》和《python類相關(guān)裝飾器小記》這兩篇文章,對ls函數(shù)用類封裝進(jìn)行代碼重構(gòu),主要是熟悉下類的一些基本概念。ls運(yùn)行結(jié)果如下:

2019-10-20_120639.png
主要的改變有以下幾點(diǎn):
- 將argparse解析器以及參數(shù)定義函數(shù)化為argparse_fun;
- 將判斷目錄是否合法也函數(shù)化為path_legal_or_not;
- 將path_legal_or_not定義為靜態(tài)方法,和argparse_fun一起封裝入ClassArgparse類中;
- LsCommand類中用slot屬性插槽(屬性插槽是我自己對其的稱呼,勿隨意效仿哈)將屬性列表式存放。
代碼直接貼出如下
# -*- encoding=UTF-8 -*-
__author__ = 'wjj1982'
__date__ = '2019/10/13 10:37'
__product__ = 'PyCharm'
__filename__ = 'ls'
import argparse
import os
import time
import prettytable
class ClassArgparse(object):
# def __init__(self):
def argparse_fun(self):
# 定義一個(gè)參數(shù)解析器
parser = argparse.ArgumentParser(prog='ls', usage='ls.py [-h -a -s -t -r]', add_help=True,description='wjj自寫win下的ls命令')
# 獲取參數(shù)解析器,默認(rèn)add_help就是True
# 給解析器加入位置參數(shù)path和選項(xiàng)參數(shù) a和r
parser.add_argument('path', nargs='?', default='.', help='文件夾路徑') # 增加位置參數(shù)path
parser.add_argument('-a', '--all', action='store_true', help='列出文件夾下的文件') # 增加選項(xiàng)參數(shù)-a
parser.add_argument('-s', '--sorted', action='store_true', help='列出按文件大小排序后的文件夾下的文件') # 增加選項(xiàng)參數(shù)-s
parser.add_argument('-t', '--time', action='store_true', help='列出按時(shí)間排序后的文件夾下的文件') # 增加選項(xiàng)參數(shù)-t
parser.add_argument('-r', '--recursion', action='store_true', help='循環(huán)列出文件夾下所有文件') # 增加選項(xiàng)參數(shù)-r
# 用解析器解析命令行輸入的參數(shù)
# args = parser.parse_args() # 分析參數(shù),空表示無參數(shù)傳入,也可以帶參傳入,例如:args = parser.parse_args(('-r','-a','.'))
return parser.parse_args()
@staticmethod
def path_legal_or_not(path):
# 判斷路徑是否合法
directory = path
# 如果指定目錄不存在,拋出異常
if not os.path.exists(directory):
raise ValueError(f'{directory} does`t exist') # 等同于 raise ValueError('{} does`t exist'.format(directory))
# 如果directory不是一個(gè)目錄,拋出異常
if not os.path.isdir(directory):
raise ValueError(f'{directory} is not a directory')
class LsCommand(object):
__slots__ = ('show_all', 'recursion', 'directory', 'show_sorted_size', 'show_sorted_time')
def __init__(self, show_all=False, directory='.', recursion=False, show_sorted_size=False, show_sorted_time=False):
'''
:param show_all: 是否顯示隱藏文件
:param directory: 指定的文件目錄
:param recursion: 是否遞歸顯示目錄下的文件
'''
self.show_all = show_all
self.recursion = recursion
self.directory = os.path.abspath(directory)
self.show_sorted_size = show_sorted_size
self.show_sorted_time = show_sorted_time
def list_dir(self):
'''
處理目錄
:param directory: 文件目錄
:param grade: 目錄層級
:param placeholder: 子目錄文件前面的占位符
:return:
'''
# 判斷是否為文件夾
# grade是否增加過了
# os.listdir: 列出當(dāng)前文件夾下面的所有文件和文件夾
# 遍歷目錄下的文件,文件夾
list_temp2 = []
list_temp3 = []
file_id = 0
if self.show_all:
for i in os.listdir(self.directory):
list_temp1 = []
list_temp1.append(file_id)
list_temp1.append(i)
list_temp1.append(os.path.getsize(self.directory + '\\' + i))
list_temp1.append(
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.stat(self.directory + '\\' + i).st_ctime)))
file_id += 1
if os.path.isdir(self.directory + '\\' + i):
list_temp2.append(list_temp1)
else:
list_temp3.append(list_temp1)
elif not self.show_all:
for i in os.listdir(self.directory):
list_temp1 = []
list_temp1.append(file_id)
list_temp1.append(i)
list_temp1.append('--')
list_temp1.append('--')
file_id += 1
if os.path.isdir(self.directory + '\\' + i):
list_temp2.append(list_temp1)
else:
list_temp3.append(list_temp1)
return list_temp2, list_temp3
# 按照文件大小或者按照時(shí)間進(jìn)行排序,返回排序后的文件列表
def sorted_file(self, list_temp2, list_temp3):
if self.show_sorted_size:
list_temp2 = sorted(list_temp2, key=lambda x: x[2])
list_temp3 = sorted(list_temp3, key=lambda x: x[2])
if self.show_sorted_time:
list_temp2 = sorted(list_temp2, key=lambda x: x[3])
list_temp3 = sorted(list_temp3, key=lambda x: x[3])
return list_temp2, list_temp3
# 定義運(yùn)行主函數(shù)
def run(self):
'''
運(yùn)行l(wèi)s命令
:return:
'''
list_temp2, list_temp3 = self.list_dir()
if self.show_sorted_size or self.show_sorted_time:
list_temp2, list_temp3 = self.sorted_file(list_temp2, list_temp3)
return list_temp2, list_temp3
def main():
# args = parser.parse_args()
arg_class = ClassArgparse()
args = arg_class.argparse_fun()
ClassArgparse.path_legal_or_not(args.path)
# arg_class.path_legal_or_not(args.path)
# args = argparse_fun()
# path_legal_or_not(args.path)
ls = LsCommand(args.all, args.path, args.recursion, args.sorted, args.time)
table_x = prettytable.PrettyTable(["ID", "目錄名", "目錄大小", "創(chuàng)建時(shí)間"])
table_x.align['目錄名'] = 'l'
table_y = prettytable.PrettyTable(["ID", "文件名", "文件大小", "創(chuàng)建時(shí)間"])
table_y.align['文件名'] = 'l'
list_dir_file = ls.run()
for i in list_dir_file[0]:
table_x.add_row(i)
for i in list_dir_file[1]:
table_y.add_row(i)
print(table_x)
print(table_y)
if __name__ == '__main__':
main()