1 """!Contains the Listing class, which emulates "ls -l"."""
7 import os,stat,StringIO,grp,pwd,time
10 """!Imitates the shell "ls -l" program.
12 Imitate ls -l, but with a longer mtime string:
14 print Listing("/usr/local")
17 To include files whose names begin with "." add hidden=True:
19 print Listing("/usr/local",hidden=True)
22 To log messages related to failures of lstat and readlink, pass
25 print Listing("/usr/local",hidden=True,logger=logger)
27 def __init__(self,path=".",hidden=False,logger=None):
28 """!Constructor for Listing:
29 @param path The directory path to list.
30 @param hidden If True, files with names beginning with "." are listed.
31 @param logger A logging.Logger for error messages."""
34 self.
list(hidden=bool(hidden),logger=logger)
36 """!Iterates over filenames in the listed directory."""
37 for name
in self.contents.iterkeys():
40 """!Iterates over name,data pairs in the listed directory. The
41 "data" will be a tuple containing the output of lstat and the
42 output of readlink."""
43 for (name,data)
in self.contents.iteritems():
46 """!Iterates over filenames in the listed directory."""
47 for name
in self.contents.iterkeys():
50 def list(self,hidden=False,logger=None):
51 """!Updates the internal data structures with a new listing of
52 the directory. Arguments are the same as for the constructor.
53 @param hidden If True, files with names beginning with "." are listed.
54 @param logger A logging.Logger for error messages."""
57 listing=os.listdir(path)
60 if item[0]==
'.' and not hidden:
63 loc=os.path.join(path,item)
66 except EnvironmentError
as e:
67 if logger
is not None:
69 "%s: cannot lstat: %s"%(loc,str(e)),exc_info=
True)
71 if not stat.S_ISLNK(lstat.st_mode):
72 contents[item]=(lstat,
None)
75 linkpath=os.readlink(loc)
76 except EnvironmentError
as e:
77 if logger
is not None:
79 "%s: cannot readlink: %s"%(loc,str(e)),exc_info=
True)
80 contents[item]=(lstat,
"(**UNKNOWN**)")
82 contents[item]=(lstat,linkpath)
85 """!Generates an ls -l style listing of the directory."""
89 for (name,item)
in c.iteritems():
91 for col
in xrange(len(row)-1):
92 sizes[col]=max(sizes[col],len(row[col]))
94 format=
' %%%ds'*6+
' %%s\n'
96 format=format%tuple(sizes)
104 def _stritem(self,name,item):
105 """!This is an internal implementation function. Do not call
106 it directly. It generates one line of ls output as a tuple of
107 strings, one string per column of information (the mtime is
108 one column). The __str__ turns the lines into one big string.
109 @param name the filename
110 @param item details about the file
111 @returns data for each column of the listing"""
114 if linkpath
is None: linkpath=
'(**UNKNOWN**)'
120 if stat.S_ISDIR(mode): s+=
'd'
121 elif stat.S_ISCHR(mode): s+=
'c'
122 elif stat.S_ISBLK(mode): s+=
'b'
123 elif stat.S_ISFIFO(mode): s+=
'p'
124 elif stat.S_ISLNK(mode): s+=
'l'
125 elif stat.S_ISSOCK(mode): s+=
's'
129 s+=(
'r' if mode&stat.S_IRUSR else '-')
130 s+=(
'w' if mode&stat.S_IWUSR
else '-')
131 if mode&stat.S_IXUSR:
132 if mode&stat.S_ISUID:
136 elif mode&stat.S_ISUID:
142 s+=(
'r' if mode&stat.S_IRGRP else '-')
143 s+=(
'w' if mode&stat.S_IWGRP
else '-')
144 if mode&stat.S_IXGRP:
145 if mode&stat.S_ISGID:
149 elif mode&stat.S_ISGID:
156 s+=(
'r' if mode&stat.S_IROTH else '-')
157 s+=(
'w' if mode&stat.S_IWOTH
else '-')
158 if mode&stat.S_IXOTH:
159 if mode&stat.S_ISVTX:
163 elif mode&stat.S_ISVTX:
168 nlink=str(int(lstat.st_nlink))
171 size=str(int(lstat.st_size))
172 when=time.asctime(time.localtime(lstat.st_mtime))
173 if stat.S_ISLNK(lstat.st_mode):
174 return (s,nlink,username,groupname,size,when,name+
' -> '+linkpath)
176 return (s,nlink,username,groupname,size,when,name)
179 def _groupname(self,gid):
180 """!Return the group name for a group ID from getgrgid."""
183 return str(gr.gr_name)
184 except (KeyError,ValueError,EnvironmentError):
187 def _username(self,uid):
188 """!Return the user name for a group ID from getpwuid."""
191 return str(pw.pw_name)
192 except (KeyError,ValueError,EnvironmentError):
Imitates the shell "ls -l" program.
def __init__
Constructor for Listing:
def _username(self, uid)
Return the user name for a group ID from getpwuid.
def iteritems(self)
Iterates over name,data pairs in the listed directory.
def __iter__(self)
Iterates over filenames in the listed directory.
def list
Updates the internal data structures with a new listing of the directory.
def iterkeys(self)
Iterates over filenames in the listed directory.
def _groupname(self, gid)
Return the group name for a group ID from getgrgid.
def _stritem(self, name, item)
This is an internal implementation function.
def __str__(self)
Generates an ls -l style listing of the directory.