6

问题:

如何有效地使用stat函数来获得有意义的文件权限(用户、组和其他)。

细节:

我正在查询文件权限,如下所示:

statInfo = os.stat
permissions = stat.S_IMODE ( os.stat ( 'fooBar.txt' ).st_mode )

这将返回十进制形式的权限。所以如果fooBar.txt有八进制文件权限0700,这里permissions设置为十进制值448。我想要的是为每个权限设置 9 个变量(ownerRead, ownerWright, ownerExecute, groupRead,...)如果我要这样做,我会使用这样的蛮力方法:

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

有没有更有效的方法来做到这一点而不必转换为八进制,因为这个函数会被调用很多次?

4

3 回答 3

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)
...
于 2012-05-24T16:35:34.287 回答
5

stat使用按位 AND 和模块中的常量:

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)
...

更具可读性。

于 2012-05-24T16:43:36.600 回答
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)
于 2013-12-24T01:12:19.650 回答