如何有效地使用stat函数获取有意义的文件权限(用户,组和其他)。
我正在查询文件权限,如下所示:
statInfo = os.stat
permissions = stat.S_IMODE ( os.stat ( 'fooBar.txt' ).st_mode )
以十进制形式返回权限。因此,如果fooBar.txt
具有八进制文件权限0700
,则此处permissions
设置为十进制值448
。我想要的是为每个权限设置9个变量(ownerRead
,ownerWright
,ownerExecute
,groupRead
,...)如果我要这样做,我' d使用像这样的蛮力方法:
statInfo = os.stat
permissions = stat.S_IMODE ( os.stat ( 'fooBar.txt' ).st_mode )
octPermissions = oct ( permissions )
ownerRead = octPermissions [1] >= 4
ownerWrite = octPermissions [1] == 2 or octPermissions [1] == 6 or octPermissions [1] == 3 or
ownerExecute = octPermissions [1] == 1 or octPermissions [1] == 5 or octPermissions [1] == 3
有没有更有效的方法来执行此操作而不必转换为八进制,因为这个函数会被调用很多?
答案 0 :(得分:5)
您可以使用按位AND运算符:
m = os.stat('fooBar.txt').st_mode
otherExec = bool(m & 0001)
otherWrite = bool(m & 0002)
otherRead = bool(m & 0004)
groupExec = bool(m & 0010)
groupWrite = bool(m & 0020)
groupRead = bool(m & 0040)
...
答案 1 :(得分:5)
使用按位AND和stat
module中的常量:
import stat
import os
mode = os.stat('fooBar.txt').st_mode
otherRead = bool(mode & stat.S_IROTH)
otherWrite = bool(mode & stat.S_IWOTH)
otherExec = bool(mode & stat.S_IXOTH)
...
更具可读性。
答案 2 :(得分:3)
我把它放在一个获得UNIX权限的函数中:
import os
from stat import (S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP,
S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH)
def bit2int(bit):
return int(oct(bit))
def convert_st_mode(st_mode):
bits = (S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP,
S_IROTH, S_IWOTH, S_IXOTH)
mode = "%03d" % sum(int(bool(st_mode & bit)) * bit2int(bit) for bit in bits)
return mode
def get_unix_permissions(pth):
mode = convert_st_mode(os.stat(pth).st_mode)
return mode
用法:
mode = get_unix_permissions("somefile")
print(mode)