如何从“-rw-r--r--”回到 33188?

How to get from '-rw-r--r--' back to 33188?

Python 有一个辅助函数 stat.filemode to go from the st_mode (integer) as reported by os.stat 转换为熟悉的“stringy”格式(我不知道这种表示是否有合适的名称)。

>>> stat.filemode(0o100644)
'-rw-r--r--'

是否有任何“unfilemode”辅助函数可以走另一条路?

>>> unfilemode('-rw-r--r--')
33188

这是我尝试过的方法,但它产生了错误的结果。那不是正确处理表示文件类型的第一个字符,也没有处理粘滞位等

table = {
    ord('r'): '1',
    ord('w'): '1',
    ord('x'): '1',
    ord('-'): '0',
}

def unfilemode(s):
    return int(s.translate(table), 2)

Python是开源的,你可以阅读stat模块的源代码并编写反函数。

参见:https://github.com/python/cpython/blob/master/Lib/stat.py#L112

import stat

def un_filemode(mode_str):
    mode = 0
    for char, table in zip(mode_str, stat._filemode_table):
        for bit, bitchar in table:
            if char == bitchar:
                mode |= bit
                break
    return mode

请注意,我正在 "naughty" 访问 stat 模块的私有成员。通常的注意事项适用。

另请注意,stat.filemode 的文档无论如何都是不正确的,因为 0o100000 在技术上不是文件模式的一部分,它是文件类型 S_IFREG。来自 inode(7):

POSIX refers to the stat.st_mode bits corresponding to the mask S_IFMT (see below) as the file type, the 12 bits corresponding to the mask 07777 as the file mode bits and the least significant 9 bits (0777) as the file permission bits.