2011-02-08 85 views
1

我正在浏览搜索文件并列出其权限的其中一个python脚本。我仍然是一名Python学习者,在研究这段代码的同时,我遇到了以下问题:Python脚本来搜索文件

在下面的行中,的含义是什么“mode = stat.SIMODE(os.lstat(file)[ stat.ST_MODE])“? 什么是返回到“模式”?以及它如何在提供权限信息方面发挥作用?如果有人能解释这一点,将不胜感激。

此外,我需要了解该段中的嵌套for循环如何在获取所需的输出文件名和相关权限方面发挥作用?

这里“层次”的意义是什么?

非常感谢,如果有人能回答上述问题并给出相关指导。提前致谢。

整个代码为:

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 & getattr(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" 
+1

@ Ignacio嗨,基本上,我正在寻找有关我以粗体突出显示的行的答案。我研究了stat.S_IMODE的python文档,但需要更多的说明。 – Nura 2011-02-08 06:46:18

回答

1

交互式Python解释器壳,以了解他们玩弄的Python代码片段的好地方。例如,为了获得模式的东西在你的脚本:

>>> 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 

现在你知道的值,检查Python docs得到他们的意思。

以类似的方式,您可以尝试自己回答其他问题。

UPDATE:mode的值是按位不同mode flagsOR组合。嵌套循环“手动”构建这些标志的名称,使用getattr来获取它们的值,然后检查mode是否包含这些值。