gpt4 book ai didi

python - 如何从 '-rw-r--r--' 返回到 33188?

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:53 25 4
gpt4 key购买 nike

Python 有一个辅助函数 stat.filemodeos.stat 报告的 st_mode(整数)开始转换为熟悉的“字符串”格式(我不知道这种表示是否有合适的名称)。

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

请注意,我正在“调皮”并访问 stat 模块的私有(private)成员。通常的警告适用。

另请注意,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.

关于python - 如何从 '-rw-r--r--' 返回到 33188?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com