Python全栈工程师

23.2-ls命令实现2

2019-10-16  本文已影响0人  BeautifulSoulpy

想要救紫霞就必须打败牛魔王,想要打败牛魔王就必须要变成孙悟空,想要变成孙悟空就必须忘掉七情六欲,从此不能再有半点沾染。

人生就是这样:想自由地和心爱之人在一起必须要事业有成,想要事业有成就必须要抛弃天真戴上面具,当你变得有能力给心爱之人一切时,却发现找不回最初的自己,亦失去了爱的能力;

学习编程的过程中要不断的提高我们的变成能力,但不是什么事情都是我们自己做;

所以我们要不断的学习使用各种标准库;能用则用;能看一眼就看一眼,但是要适可而止;
关键是你能不能在现有的知识上封装出漂亮的函数(美观性、实用性),能不能把以前写的东西推到重新再写;

我们要练的是:有没有思路能解决遇到的问题,

总结:

  1. 字典是空间换时间;

实现ls命令功能 ,-l 、-a 、--all 、-h

实现显示路径下的文件列表;
-a和-all 显示包含.开头的文件;
-l详细列表显示
-h 和 -l 配合,人性化显示文件大小,例如1K、1G、1T等,可以认为1G=1000M
类型字符:c字符、d目录、普通文件、I软链接、b块设备、s socket文件、p pipe文件 即FIFO

# !/usr/bin/env python
# encoding:utf-8
'''
@auther:administrator

'''
import argparse,datetime,stat
from pathlib import Path

def iterdir(p:str,all=False,detail=True,human=False):
    def _getfiletype(p: Path):
        if p.is_dir():
            return 'd'
        elif p.is_block_device():
            return 'b'
        elif p.is_char_device():
            return 'c'
        elif p.is_fifo():
            return 'p'
        elif p.is_socket():
            return 's'
        elif p.is_symlink():
            return 'l'
        else:
            return '-'

    def _gethuman(w:int):  #4096sdasdsad
        units = ' KMGTPB'
        index = 0
        while w >= 1024:
            w = w//1024
            index += 1

        return "{}{}".format(w,units[index].rstrip())

    def listdir(p:str, all=False,detail=True,human=False):
        path = Path(p)
        for x in path.iterdir():
            if not all and x.name.startswith('.'):
                continue
            if detail:
                st = path.stat()
            #print(st)
            #t = _getfiletype(path)
            #mode = _getmodestr(st.st_mode)
                mode = stat.filemode(st.st_mode)
                atime = datetime.datetime.fromtimestamp(st.st_atime).strftime("%Y%m%d %H:%M:$S")
                human = _gethuman(st.st_size) if human else str(st.st_size)
                yield (mode,st.st_nlink,st.st_uid,st.st_gid,human,st.st_atime,x.name)
            else:
                yield (x.name,)
    yield from sorted(listdir(p,all,detail,human),key=lambda x:x[-1])

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        prog='ls',
        description='List information about the FILEs.',
        add_help=False)  # 获得一个参数解析器
    # ls/etc
    parser.add_argument('path', nargs='?', default='.', help='filepath')
    parser.add_argument('-l', dest='list', action='store_true', help='use a long listing format')
    parser.add_argument('-a', '--all', action='store_true', help='do not ignore entries strating with .')
    parser.add_argument('-h', '--human-readable', dest='human', action='store_true',
                        help='with -l,print sizes in human readable format(e.g., 1K 234M 2G)')
    # parser.add_argument('integers', metavar='N', type=int, nargs='+',
    #                     help='an integer for the accumulator')
    # parser.add_argument('--sum', dest='accumulate', action='store_const',
    #                     const=sum, default=max,
    #                     help='sum the integers (default: find the max)')

    args = parser.parse_args(('./venv'.split()))  # 分析参数

    l = list(iterdir(args.path,args.all,args.list,args.human))
    print(l)

#-----------------------------------------------------
[('Include',), ('Lib',), ('Scripts',), ('pyvenv.cfg',), ('t.py',), ('t2.py',), ('test5',)]  # win下信息显示不全;

import argparse,datetime,stat
from pathlib import Path

parser = argparse.ArgumentParser(
    prog='ls',
    description='List information about the FILEs.',
    add_help=False)   #获得一个参数解析器
# ls/etc
parser.add_argument('path',nargs='?',default='.',help='filepath')
parser.add_argument('-l',dest='list',action='store_true',help='use a long listing format')
parser.add_argument('-a','--all',action='store_true',help='do not ignore entries strating with .')
parser.add_argument('-h','--human-readable',dest='human',action='store_true',
                    help='with -l,print sizes in human readable format(e.g., 1K 234M 2G)')
# parser.add_argument('integers', metavar='N', type=int, nargs='+',
#                     help='an integer for the accumulator')
# parser.add_argument('--sum', dest='accumulate', action='store_const',
#                     const=sum, default=max,
#                     help='sum the integers (default: find the max)')

args = parser.parse_args(('./venv'.split()))   # 分析参数
print('---------------------------------')
parser.print_help()  # 打印帮助;
print(args)
print('---------------------------------')
print(args.all,args.list,args.path)

def iterdir(p:str,all=False,detail=True,human=False):
    def _getfiletype(p: Path):
        if p.is_dir():
            return 'd'
        elif p.is_block_device():
            return 'b'
        elif p.is_char_device():
            return 'c'
        elif p.is_fifo():
            return 'p'
        elif p.is_socket():
            return 's'
        elif p.is_symlink():
            return 'l'
        else:
            return '-'

    def _gethuman(w:int):  #4096sdasdsad
        units = ' KMGTPB'
        index = 0
        while w >= 1024:
            w = w//1024
            index += 1

        return "{}{}".format(w,units[index].rstrip())

    def listdir(p:str, all=False,detail=True,human=False):
        path = Path(p)
        for x in path.iterdir():
            if not all and x.name.startswith('.'):
                continue
            if detail:
                st = path.stat()
            #print(st)
            #t = _getfiletype(path)
            #mode = _getmodestr(st.st_mode)
                mode = stat.filemode(st.st_mode)
                atime = datetime.datetime.fromtimestamp(st.st_atime).strftime("%Y%m%d %H:%M:$S")
                human = _gethuman(st.st_size) if human else str(st.st_size)
                print(mode,st.st_nlink,st.st_uid,st.st_gid,human,st.st_atime,x.name)
            else:
                print(x.name)


iterdir(args.path,args.all,args.list,args.human)
上一篇下一篇

猜你喜欢

热点阅读