用argparse实现ls -lha等linux命令格式展示

import argparse
from pathlib import Path
from datetime import datetime
import stat

parse = argparse.ArgumentParser(prog='ls', add_help=False, description='list directory contents') #获得一个解析器参数
parse.add_argument('path', nargs='?', default='.', help="directory") #用?代表位置参数,可有可无
parse.add_argument('-l', action='store_true', dest='long', help='use a long listing format')
parse.add_argument('-a', '--all', action='store_true', help='show all files, do not ignore entries starting with .')
parse.add_argument('-r', '--reverse', action='store_true', help='reverse order while sorting')
parse.add_argument('-h', '--human-readable', action='store_true', dest='human',
                   help='with -l, print sizes in human readable format')

def listdir(path, all=False, detail=False, reverse=False, human=False):
    '''详细列出本目录'''
    def _gethuamn(size:int):   #文件大小以human format显示
        untils = ' KMGT'
        depth = 0
        while size > 1000 and depth < len(untils) - 1:  #当前size大于1000,且depth不是最后一个进入循环
            depth += 1
            size //= 1000
        return '{}{}'.format(size, untils[depth] if depth else '')

    def _listdir(path, all, detail, reverse, human):
        p = Path(path)
        for i in p.iterdir():
            if not all and i.name.startswith('.'):   #去除不显示所有和以点开头的隐藏文件
                continue

            if not detail:
                yield (i.name,)
            else:
                st = i.stat()      # 文件的相关信息
                mode = stat.filemode(st.st_mode)    # 通过Python自带的模块得到文件权限
                mtime = datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S')
                size = st.st_size if not human else _gethuamn(st.st_size)
                yield (mode, st.st_nlink, st.st_uid, st.st_gid, size, mtime, i.name)

    return sorted(_listdir(path, all, detail, reverse, human), key=lambda x:x[len(x)-1], reverse=reverse)

if __name__ == '__main__':
    args = parse.parse_args()  # 分析参数, 同时传入可迭代参数
    # print(args)
    # parse.print_help()       #打印帮助
    files = listdir(args.path, args.all, args.long, args.reverse, args.human)
    print(*files, sep='\n')


##测试python xxx.py -lha
##测试python xxx.py -lha /tmp















 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值