ls命令的python不完全实现
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | from pathlib import Path import argparse,sys,datetime,stat,platform def showdir(path:str= '.' ,all=False,detail=False,human=False,reverse=False): def convert_type_mode(file:Path)->str: return stat.filemode(file.stat().st_mode) def convert_mode(mode: int )->str: # 转换文件权限 modelist=list( 'rwx' *3) modestr=bin(mode)[-9:] s= '' for i,c in enumerate(modestr): if c == '1' : s+=modelist[i] else : s+= '-' return s # b=Path().stat().st_mode # def _getmodestr(mode:int)->str: # modelist=list('rwx'*3) # m=mode & 0o777 # print('mode',mode) # print(m,oct(m),bin(m)) # s='' # for i,v in enumerate(bin(m)[-9:]): # 将int转换为str进行迭代 # if v == '1': # s+=modelist[i] # else: # s+='-' # return s # # b = Path().stat().st_mode # def _getmodestr(mode: int) -> str: # 移位操作 # modelist = list('rwx' * 3) # modedict = dict(zip(range(9), modelist)) # 倒序字典 # m = mode & 0b111111111 # s = '' # for i in range(8, -1, -1): # if m >> i & 1: # s += modedict.get(8 - i) # else: # s += '-' # return s def convert_type(file:Path)->str: # 转换文件类型 s= '' if file.is_symlink(): s= 'l' elif file.is_dir(): s= 'd' elif file.is_char_device(): s= 'c' elif file.is_fifo(): s= 'p' elif file.is_socket(): s= 's' elif file.is_block_device(): s= 'b' else : s= '-' return s def convert_time(f: float )->str: # 转换时间格式 return datetime.datetime.fromtimestamp(f).strftime( '%Y-%m-%d %H:%M:%S' ) def convert_human(size: int )->str: # 转换size为human_readable units=[ '' ]+list( 'KMGTPE' ) #units=' KMGTPE' depth=-1 # while size >= 1000: # size//=1000 # depth+=1 # return '{}{}'.format(size,units[depth]) def _human(size: int )->str: nonlocal depth depth+=1 if size<1000: return '{}{}' .format(size,units[depth]) return _human(size //1000) return '{:>5}' .format(_human(size)) def _get_owner_group(file:Path): # 得到属主和属组 if platform.system() == 'Linux' : return '{} {}' .format(file.owner,file. group ) else : return '{} {}' .format(file.stat().st_uid,file.stat().st_gid) def _showdir(path:str= '.' ,all=False,detail=False,human=False): p=Path(path) # p.owner for file in p.iterdir(): # yield file.name # todo -rw-r--r--. 1 root root 127 Nov 14 10:13 bb.py # todo Linux and Windows Path().stat() # os.stat_result(st_mode=33188, st_ino=33574979, st_dev=64768, st_nlink=1, st_uid=0, st_gid=0, st_size=33, st_atime=1573697346, st_mtime=1573697281, st_ctime=1573697281) # os.stat_result(st_mode=16895, st_ino=1407374883707564, st_dev=778327066, st_nlink=1, st_uid=0, st_gid=0, st_size=24576, st_atime=1600576373, st_mtime=1600531501, st_ctime=1535871988) # if not all: # if file.name.startswith('.'): # continue if not all and file.name.startswith( '.' ): continue if detail: st=file.stat() human_size=str(st.st_size) if human: # 在detail(-l)为True时,human(-h)才进行判断 human_size=convert_human(st.st_size) yield (convert_type(file)+convert_mode(st.st_mode),st.st_nlink,_get_owner_group(file),human_size,convert_time(st.st_atime),file.name) else : yield (file.name,) yield from sorted(_showdir(path,all,detail,human),key=lambda b:b[-1],reverse=reverse) # 创建参数解析器实例 parser=argparse.ArgumentParser(prog= 'ls' ,add_help=False,description= 'i\'m a decscription' ) parser.add_argument( '-l' , '--list' ,action= "store_true" ,help= 'list detail' ) parser.add_argument( '--all' , '-a' ,action= "store_true" ,help= 'show all files' ) parser.add_argument( '-h' ,action= 'store_true' ,help= 'human readable size' ) parser.add_argument( '-r' ,action= 'store_true' ,help= 'reverse' ) # 位置参数,可有可无,,缺省值'.' parser.add_argument( 'path' ,nargs= '?' , default = '.' ,help= 'input a directory' ) if __name__ == '__main__' : # args=parser.parse_args('c:/users/flirt\x20flare -lh'.rsplit(maxsplit=1)) # 分析参数,传入可迭代参数 args=parser.parse_args() print( 'args=' ,args) # 打印 namespace 中收集的参数 print( 'args.path={}\nargs.all={}\nargs.list={}\nargs.h={}\nargs.r={}' .format(args.path,args.all,args.list,args.h,args.r)) parser.print_help() for st in showdir(args.path,all=args.all,detail=args.list,human=args.h,reverse=args.r): print(str(st).strip( '()' )) # def listdir(path,all=False,detail=False): # """list detail of the path""" # p=Path(path) # for i in p.iterdir(): # if not all and i.name.startswith('.'): # continue # if not detail: # yield (i.name) # else: # stat=i.stat() # mode=_getfiletype(i)+_getfilemode(stat.st_mode) # atime=datetime.datetime.fromtimestamp(stat.st_atime).strftime('%Y-%m-%d %H:%M:%S') # yield (mode,stat.st_nlink,stat.st_uid,stat.st_gid,stat.st_size,atime,i.name) # yield from sorted(_listdir(path,all,detail,human),key=lambda x:x[len(x)-1]) if __name__ == '__main__' : args=parser.parse_args() print(args) parser.print_help() files=listdir(args.path,args.all,args.l,args.human_readable) print(list(files)) |
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律