代码
#!/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参数输入想要显示的路径
效果对比:
除了显示时间的方式和显示顺序不一样,其他都是一样的