2011-02-08 73 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是否包含這些值。