Argparse模块的使用:ls功能的实现

Argparse模块是用于Python中命令行参数解析的模块
以下代码为ls功能的实现

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

#获得一个参数解析器
parser = argparse.ArgumentParser(
    prog = 'ls',
    description = 'List information about the FILEs',
    add_help = False
)

#添加参数
parser.add_argument('path', nargs='?', default='.',
                    help='filepath')
                    #位置参数,?表示可有可无,缺省值,帮助文本
parser.add_argument('-l', dest='long', action='store_true',
                    help='use a long listing format')
parser.add_argument('-a', '--all', action='store_true',
                    help='do not ignore entries starting with .')
parser.add_argument('-h', '--human-readable', action='store_true',
                    help='with -l, print sizes in human readable format')

def listdir(path, all=False, detail=False, human=False):
    def _gethuman(size:int):
        units = 'KMGTP'
        depth = 0
        while size >= 10:
            size = size // 1000
            depth += 1
        return '{}{}'.format(size, units[depth])

    def _listdir(path, all=False, detail=False, human=False):
    '''详细列出目录'''
        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)
                atime = datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S')
                size = str(st.st_size) if not human else _gethuman(st.st_size)
                yield (mode, st.st_nlink, st.st_uid, st.st_gid, size, atime, i.name)
	#排序
    yield from sorted(_listdir(path, all, detail, human), key=lambda x: x[len(x)-1])

if __name__ == '__main__':
    args = parser.parse_args() #分析参数,传入可迭代的参数
    print(args)
    parser.print_help()
    files = listdir(args.path, args.all, args.long, args.human_readable)
    print(list(files))
    

测试:python ***.py -lah

以上代码小结:

  1. 创建parser=ArgumentParser( )对象
  2. 添加参数add_argument( )
  3. 自定义功能函数func( )
  4. args = parser.parse_args( )
  5. 调用函数func(args)

你可能感兴趣的:(Python)