Python脚本查找文件

1 投票
1 回答
3175 浏览
提问于 2025-04-16 11:25

我在看一个用Python写的脚本,这个脚本用来搜索文件并列出它们的权限。因为我还是个Python初学者,所以在学习这段代码时,遇到了一些问题:

在下面的代码行中,“mode=stat.SIMODE(os.lstat(file)[stat.ST_MODE])” 这行是什么意思?“mode” 返回的值是什么?它是怎么提供权限信息的?如果有人能解释一下,我会很感激。

另外,我还想了解这个部分中的嵌套for循环是如何工作的,以便显示文件名和相关权限的?

还有这里的“level”有什么重要性?

如果有人能回答以上问题并提供相关指导,我将非常感激。谢谢!

完整代码如下:

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 个回答

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文档,了解它们的含义。

你也可以用类似的方法自己尝试回答其他问题。

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

撰写回答