2020撸python--argparse列出D盘目录详情

from pathlib import Path
import argparse
import datetime
import stat


def convert_mode(mode:int):
    modelist = ['r', 'w', 'x', 'r', 'w', 'x']
    modestr = bin(mode)[-9:]
    ret = ""
    for i, c in enumerate(modestr):
        if c == 'l':
            ret += modelist[i]
        else:
            ret += '-'
    return ret


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, human=False):
    """

    :param path:
    :param all:
    :param detail:
    :param human:
    :return:
    """
    p = Path(path)
    for file in p.iterdir():
        if not all and str(file.name).startswith('.'): # .开头不打印 --all
            continue
        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)
        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('-h', action='store_true')
parser.add_argument('-a','--all',action='store_true')

if __name__ == '__main__':
    args = parser.parse_args(('D:/', '-l'))

    parser.print_help()

    print('args=', args)

    for st in showdir(args.path, args.all, args.l, args.h):
        print(st)
原文地址:https://www.cnblogs.com/bk770466199/p/12142443.html