[python]代码库
import datetime
from pathlib import Path
import argparse
import stat
def convert_mode(mode:int):
modelist = ['r', 'w', 'x', 'r', 'w', 'x', 'r', 'w', 'x']
modestr = bin(mode)[-9:] #'110 110 100'
ret = ""
for i,c in enumerate(modestr):
if c == '1':
ret += modelist[i]
else:
ret += '-'
return ret
# d - s p l c b
def convert_type(file:Path):
ret = ""
if file.is_symlink():
ret = "l"
elif file.is_fifo():
ret = "p"
elif file.is_socket():
ret = "s"
else:
ret = '-'
return ret
parser = argparse.ArgumentParser(prog='ls',add_help=False,description='list contens directory') #构造解析器
parser.add_argument('path',nargs='?',default='.') #位置参数
parser.add_argument('-l',action='store_true')
parser.add_argument('-h',action='store_true')
parser.add_argument('-a','--all',action='store_true')
# drwxrwxr-x. 3 python python 4096 Jul 21 2020 magedu
def showdir(path='.',all=False, detail=False, human=False):
p = Path(path)
for file in p.iterdir():
if not all and file.name.startswith('.'): # .开头,不打印
continue
# -l 解决-l的问题
if detail:
st = file.stat()
yield (stat.filemode(st.st_mode),st.st_nlink,st.st_uid,st.st_gid,st.st_size,datetime.datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H-%M-%S'),file.name)
#yield xxxx
else:
yield (file.name,)
# ls [path] [-l] [-a]
if __name__ == "__main__":
args = parser.parse_args(("e:/","-lah"))
print('args=',args)
parser.print_help()
for st in showdir(args.path,args.all,args.l,args.h):
print(st)
初级程序员
by: 云代码会员 发表于:2021-06-21 22:30:24 顶(0) | 踩(0) 回复
饿
回复评论