我需要一个解决方案如何在python脚本中打印出文件权限。我们的想法是将shell命令$: ls -l
传递给一个python脚本,我将从那里用"其他解释"打印出这些行。例如
-rwxrwxr-x
另外的解释是:
Owner of the file has reading rights, writing right, but doesn't have execution rights.
Group has reading rights, writing right and execution rights.
那么,除了涵盖谁拥有什么权利的所有可能情况之外,除了用if
条件检查每个案例之外,还有更简单的方法吗?
答案 0 :(得分:1)
以下是一些可以帮助您入门的代码。
我们首先创建一个名为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