用于搜索文件的 Python 脚本

标签 python search file permissions

我正在浏览一个用于搜索文件并列出其权限的 python 脚本。我还是一个Python学习者,在学习这段代码时,我遇到了以下问题:

在下面的行中,行“mode=stat.SIMODE(os.lstat(file)[stat.ST_MODE])”的含义是什么? 返回到 "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"

最佳答案

交互式 Python 解释器 shell 是一个很好的地方,可以使用 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来了解它们的含义。

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

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

关于用于搜索文件的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4930179/

相关文章:

python - 使用 AzureMachineLearningFileSystem 更新时出现 NotImplementedError

python - 动态添加属性到 Django 模型

php - Laravel 5.3 中的搜索栏以过滤表格

c# - 在 C# 中响应与文件的交互?

python - defaultdict(list) 将所有值连接到一个列表中

打印不同的python基本代码

database - 如何实现图片库的颜色搜索?

php - 将命名参数与 PDO 一起用于 LIKE

java - 检查文件是否更改名称

excel - 保存工作簿的 "backup copy"而不提交对 Excel 的更改?