import argparse
from pathlib import Path
from datetime import datetime
import stat
parse = argparse.ArgumentParser(prog='ls', add_help=False, description='list directory contents') #获得一个解析器参数
parse.add_argument('path', nargs='?', default='.', help="directory") #用?代表位置参数,可有可无
parse.add_argument('-l', action='store_true', dest='long', help='use a long listing format')
parse.add_argument('-a', '--all', action='store_true', help='show all files, do not ignore entries starting with .')
parse.add_argument('-r', '--reverse', action='store_true', help='reverse order while sorting')
parse.add_argument('-h', '--human-readable', action='store_true', dest='human',
help='with -l, print sizes in human readable format')
def listdir(path, all=False, detail=False, reverse=False, human=False):
'''详细列出本目录'''
def _gethuamn(size:int): #文件大小以human format显示
untils = ' KMGT'
depth = 0
while size > 1000 and depth < len(untils) - 1: #当前size大于1000,且depth不是最后一个进入循环
depth += 1
size //= 1000
return '{}{}'.format(size, untils[depth] if depth else '')
def _listdir(path, all, detail, reverse, human):
p = Path(path)
for i in p.iterdir():
if not all and i.name.startswith('.'): #去除不显示所有和以点开头的隐藏文件
continue
if not detail:
yield (i.name,)
else:
st = i.stat() # 文件的相关信息
mode = stat.filemode(st.st_mode) # 通过Python自带的模块得到文件权限
mtime = datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S')
size = st.st_size if not human else _gethuamn(st.st_size)
yield (mode, st.st_nlink, st.st_uid, st.st_gid, size, mtime, i.name)
return sorted(_listdir(path, all, detail, reverse, human), key=lambda x:x[len(x)-1], reverse=reverse)
if __name__ == '__main__':
args = parse.parse_args() # 分析参数, 同时传入可迭代参数
# print(args)
# parse.print_help() #打印帮助
files = listdir(args.path, args.all, args.long, args.reverse, args.human)
print(*files, sep='\n')
##测试python xxx.py -lha
##测试python xxx.py -lha /tmp