[python]代码库
from pathlib import Path
import argparse
import datetime
import stat
def convert_mode(mode:int):
modelist = ['r', 'w', 'x', 'r', 'w', 'x', 'r', 'w', 'x']
modestr = bin(mode)[-9:] # '664' '110110100'
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
def showdir(path='.',all=False,detail=False):
p = Path(path)
for file in p.iterdir():
if not all and str(file.name).startswith('.'): # .开头不打印
continue
# -l
# -rw-rw-r-- 1 python python 14852 Nov 17 22:32 Untitled63.ipynb
if detail:
st = file.stat()
yield (stat.filemode(st.st_mode),st.st_nlink,file.owner(),file.group(),st.st_size,datetime.datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S'),file.name)
else:
yield file.name
parser = argparse.ArgumentParser(prog='ls',add_help=False,description='list all files') #构造解析器
parser.add_argument('path',nargs='?',default='.',help='path help')
parser.add_argument('-l',action='store_true')
parser.add_argument('-a','--all',action='store_true')
if __name__ == "__main__":
#ls
# showdir('f:/')
args = parser.parse_args(('.','-la')) #e:/为指定的目录,这个可以替换为你自己的目录
parser.print_help()
print('args=',args)
print(args.path,args.l,args.all)
for st in showdir(args.path,args.all,args.l):
print(st)