我需要一个如何在 python 脚本中打印出文件权限的解决方案。这个想法是将 shell 命令 $: ls -l 传递给 python 脚本,从那里我将打印出带有“附加解释”的行。例如
-rwxrwxr-x
额外的解释是:
文件的所有者有读权限、写权限,但没有执行权限。 组有读权限、写权限和执行权限。
那么,除了用 if 条件检查每个案例之外,有没有更简单的方法来做到这一点,而不是涵盖所有可能的谁拥有什么权利的案例?
请您参考如下方法:
这里有一些代码可以帮助您入门。
我们首先创建一个名为 modes 的列表,其中包含谁拥有权限以及他们拥有的权限类型的所有组合。然后我们并行遍历模式字符串和 modes 列表,如果模式字符串没有 -,则从 modes 中获取相关组合> 在那个位置。
modes = [(who, kind) for who in ('user', 'group', 'others')
for kind in ('read', 'write', 'execute')]
def explain_modestring(modestring):
return ', '.join([' can '.join(t)
for c, t in zip(modestring[1:], modes) if c != '-'])
for s in ('-rwxrwxrwx', '-rwxr-xr--', '-r--------'):
print(s, explain_modestring(s))
输出
-rwxrwxrwx user can read, user can write, user can execute, group can read, group can write, group can execute, others can read, others can write, others can execute
-rwxr-xr-- user can read, user can write, user can execute, group can read, group can execute, others can read
-r-------- user can read
