python实现linux下ls -l的命令

代码

#!/usr/bin/env python3
#coding=utf-8
import os
import shutil
from stat import *
import pwd
import grp
import traceback
import time

def llist(path='.'):
    try:
        for name in os.listdir(path):
            # get stat info
            si = os.stat(os.path.join(path,name))
            # print file type
            if(S_ISREG(si.st_mode)):
                print("-"),
            elif(S_ISLNK(si.st_mode)):
                print("l"),
            elif(S_ISDIR(si.st_mode)):
                print("d"),
            # print rwx permission
            perstr = ""
            perstr += ("r" if (S_IRUSR & si.st_mode) else "-")
            perstr += ("w" if (S_IWUSR & si.st_mode) else "-")
            perstr += ("x" if (S_IXUSR & si.st_mode) else "-")
            perstr += ("r" if (S_IRGRP & si.st_mode) else "-")
            perstr += ("w" if (S_IWGRP & si.st_mode) else "-")
            perstr += ("x" if (S_IXGRP & si.st_mode) else "-")
            perstr += ("r" if (S_IROTH & si.st_mode) else "-")
            perstr += ("w" if (S_IWOTH & si.st_mode) else "-")
            perstr += ("x" if (S_IXOTH & si.st_mode) else "-")
            print(perstr),
            # print links num
            print("{: >2}".format(si.st_nlink)),
            # get user name
            #print(" ", pwd.getpwuid(si.st_uid).pw_name),
            # > 左对齐 >右对齐 ^居中对齐
            print("{: >4}".format(pwd.getpwuid(si.st_uid).pw_name)),
            # get group name
            print("{: >4}".format(grp.getgrgid(si.st_gid).gr_name)),
            # print file size
            # > 左对齐 >右对齐 ^居中对齐
            print("{: >4}".format(si.st_size)),
            print(time.ctime(si.st_mtime)),
            print(name)
    except Exception as e:
        print(traceback.format_exc())
        print("error happened:", e)

if(__name__ == "__main__"):
    parser = OptionParser()
    parser.add_option('-p', '--path', default='.', help='input the path you want list,default is .')
    opts, args = parser.parse_args()
    llist(opts.path)

支持-p参数输入想要显示的路径

效果对比:

在这里插入图片描述
除了显示时间的方式和显示顺序不一样,其他都是一样的

参考

stat模块
pwd模块
grp模块

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值