i was going through one of the python scripts that Searches for Files and lists their permissions. Im still a learner in python, and while studying this code, i encountered the following questions:
In the lines below, what is the implication of the line "mode=stat.SIMODE(os.lstat(file)[stat.ST_MODE])" ? what is the value returned to "mode" ? and how does it function in providing information of the permissions? Would be grateful if someone could explain this.
Also, I need to understand how the nested for loops within this segment work with respect to getting the desired output of diplaying the filenames and associated permissions ?
And what is the significance of "level" here ?
Would be very grateful, if anyone could answer the above questions and give any relevant guidance. Thanks in advance.
The entire code is :
import stat, sys, os, string, commands
try:
#run a 'find' command and assign results to a variable
pattern = raw_input("Enter the file pattern to search for:\n")
commandString = "find " + pattern
commandOutput = commands.getoutput(commandString)
findResults = string.split(commandOutput, "\n")
#output find results, along with permissions
print "Files:"
print commandOutput
print "================================"
for file in findResults:
mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
print "\nPermissions for file ", file, ":"
for level in "USR", "GRP", "OTH":
for perm in "R", "W", "X":
if mode & getat开发者_StackOverflow社区tr(stat,"S_I"+perm+level):
print level, " has ", perm, " permission"
else:
print level, " does NOT have ", perm, " permission"
except:
print "There was a problem - check the message above"
The interactive Python interpreter shell is a good place to play around with snippets of Python code in order to understand them. For instance, to get the mode thing in your script:
>>> import os, stat
>>> os.lstat("path/to/some/file")
posix.stat_result(st_mode=33188, st_ino=834121L, st_dev=2049L, ...
>>> stat.ST_MODE
0
>>> os.lstat("path/to/some/file")[0]
33188
>>> stat.S_IMODE(33188)
420
Now you know the values, check the Python docs to get their meaning.
In a similar way you could try to answer the other questions yourself.
UPDATE:
The value of mode
is a bitwise OR combination of different mode flags. The nested loop "manually" builds the names of these flags, uses getattr
to get their values and then checks if mode
includes these values.
精彩评论