实用:python中自我实现ls命令,选项-l -a -h,并按文件名的acscii码对文件升序排序

from pathlib import Path
import datetime
import stat
import argparse

def listdir() ->tuple:
    def _convers_human(size:int)-> str:
        depth = 0
        while size >=1000:
            size = size//1000
            depth += 1
        str1 = ' KMGTP'
        return '{}{}'.format(size,str1[depth])

    def _showdir(path:str='.',detail=False,human=False,all=False)->tuple:
        p = Path(path)
        for file in p.iterdir():
            if not all and str(file).startswith('.'):
                continue
            if detail:
                st = file.stat()
                h = str(st.st_size)
                if human:
                    h = _convers_human(st.st_size)
                #-rw-rw-r-- 1 python python 33 Jun 7 22:34 test2.txt
                md = stat.filemode(st.st_mode)
                tm = datetime.datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S')
                yield (md,st.st_nlink,file.owner(),file.group(),h,tm,file.name)
            else:
                yield (file.name,)
    yield from sorted(_showdir(args.path,args.l,args.h,args.all),key=lambda x:x[-1])

parser = argparse.ArgumentParser(prog='ls',add_help=False,description='ls:  list all files and directorys ')

parser.add_argument('path',nargs='?',default='.',help="file's path")
parser.add_argument('-l',action='store_true')
parser.add_argument('-h',action='store_true')
parser.add_argument('-a','--all',action='store_true')

args = parser.parse_args('/tmp -lha'.split())

files = listdir()

for file in files:
    for i in file:
        print(i,end=' ')
    else:
        print()

运行结果:

drwxrwxrwx 5 yzx yzx 4K 2019-06-11 14:00:13 wps 
drwx------ 2 yzx yzx 4K 2019-06-11 20:34:59 wps-yzx 

你可能感兴趣的:(python,Python学习记录,文件操作,python,pathlib)