Discuss / Python / 迄今为止练习1最佳解决方案

迄今为止练习1最佳解决方案

Topic source

遥望君山

#1 Created at ... [Delete] [Delete and Lock User]

看了评论里贴出来的解决方案,要么啰嗦,要么有错,都不能精确复现系统原始命令的结果。我在做了大量尝试,淌了很多坑以后,终于能够精确复现系统原始指令:测试结果截图(系统环境:Ubuntu 16.04.5 LTS)

import os
import time
import stat
import math
from pwd import getpwuid
from grp import getgrgid

FILE_PERMS = [
    {'r': stat.S_IRUSR, 'w': stat.S_IWUSR, 'x': stat.S_IXUSR},
    {'r': stat.S_IRGRP, 'w': stat.S_IWGRP, 'x': stat.S_IXGRP},
    {'r': stat.S_IROTH, 'w': stat.S_IWOTH, 'x': stat.S_IXOTH}
]

class Info:

    def __init__(self, name, size_width=0):
        self.width = size_width
        statinfo = os.stat(name)
        mode = statinfo.st_mode
        self.name = name
        fmt = "%b %d %H:%M"
        self.date = time.strftime(fmt, time.localtime(statinfo.st_mtime))
        self.size = statinfo.st_size
        allocated_size = statinfo.st_blocks * statinfo.st_blksize
        f_bsize = os.statvfs(name).f_bsize
        f_block_num = math.ceil(allocated_size / f_bsize)
        self.fsize = f_block_num * f_bsize // 1024
        self.user = getpwuid(statinfo.st_uid).pw_name
        self.group = getgrgid(statinfo.st_gid).gr_name
        self.nlink = statinfo.st_nlink
        self.perm = 'd' if stat.S_ISDIR(mode) else '-'
        for perm in FILE_PERMS:
            self.perm += 'r' if mode & perm['r'] else '-'
            self.perm += 'w' if mode & perm['w'] else '-'
            self.perm += 'x' if mode & perm['x'] else '-'

    def __str__(self):
        return "{} {} {} {} {:{width}} {} {}".format(
            self.perm, self.nlink, self.user, self.group,
            self.size, self.date, self.name, width=self.width)


if __name__ == '__main__':
    total = 0
    dir_list = []
    width = 0
    for x in os.listdir('.'):
        if x[0] == '.':
            continue
        item = Info(x)
        width = max(width, len(str(item.size)))
        total += item.fsize
        dir_list.append(x)

    print('total', total)
    for x in sorted(dir_list, key=lambda x: x.upper()):
        print(Info(x, width))

天小六

#2 Created at ... [Delete] [Delete and Lock User]

可以的

我去现在还有人用Ubuntu系统,16.版本不是停运了吗

遥望君山

#4 Created at ... [Delete] [Delete and Lock User]

我用的是win10自己的Ubuntu子系统,就是这个版本号。


  • 1

Reply