wim*_*wim 4 python unix file-permissions bitmask stat
Python 有一个辅助函数stat.filemode可以从st_mode报告的(整数)os.stat转换为熟悉的“字符串”格式(我不知道这种表示是否有正确的名称)。
>>> stat.filemode(0o100644)
'-rw-r--r--'
Run Code Online (Sandbox Code Playgroud)
是否有任何“unfilemode”帮助函数可以反其道而行之?
>>> unfilemode('-rw-r--r--')
33188
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的,但它产生了错误的结果。这不是正确处理表示文件类型的第一个字符,也没有处理粘滞位等
table = {
ord('r'): '1',
ord('w'): '1',
ord('x'): '1',
ord('-'): '0',
}
def unfilemode(s):
return int(s.translate(table), 2)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
请注意,我正在“调皮”并访问stat模块的私有成员。通常的警告适用。
另请注意,stat.filemode无论如何文档是不正确的,因为从0o100000技术上讲它不是文件模式的一部分,它是文件类型S_IFREG. 从inode(7):
POSIX 将掩码
S_IFMT(见下文)对应的 stat.st_mode 位 称为文件类型,将掩码 07777 对应的 12 位称为文件模式位,将最低有效 9 位(0777)称为文件权限位。