我在 Debian GNU/Linux 8 (jessie) 64 位下使用 Python 2.7.9。我只是尝试通过调用 来更改文件属性os.chflags(path, mode)
.在 Python 文档中有一个 article about the os
interface它说这种方法在 Unix 中可用,但它不适用于 Linux。 Python 总是抛出:
Traceback (most recent call last):
File "/home/lexer/py/epam/tests/main.py", line 43, in <module>
os.chflags(path_to_file(file_name), stat.SF_NOUNLINK)
AttributeError: 'module' object has no attribute 'chflags'
有一个issue很久以前就已经提出了,但我仍然不明白为什么os.chflags()
不做 chattr
命令的工作。有人能详细说明一下吗?
最佳答案
Linux 不提供 chflags
系统调用,所以 Python 不提供包装器 os.chflags()
.chattr
命令使用代码( e2fsprogs-1.42.13
的 lib/e2p/fsetflags.c
):
fd = open (name, OPEN_FLAGS);
if (fd == -1)
return -1;
f = (int) flags;
r = ioctl (fd, EXT2_IOC_SETFLAGS, &f);
if (r == -1)
save_errno = errno;
close (fd);
为文件设置扩展属性,因此如果将其移植到 Python(并使用一些 C 从
EXT2_IOC_SETFLAGS
中提取 ext2fs/ext2_fs.h
的值),您可以执行以下操作:#!/usr/bin/python2
import fcntl
import os
import struct
# Taken from ext2fs/ext2_fs.h.
EXT2_IMMUTABLE_FL = 0x00000010
EXT2_IOC_SETFLAGS = 0x40086602
fd = os.open('/var/tmp/testfile', os.O_RDWR)
f = struct.pack('i', EXT2_IMMUTABLE_FL)
fcntl.ioctl(fd, EXT2_IOC_SETFLAGS, f);
os.close(fd)
等等:
[tim@passepartout ~]$ lsattr /var/tmp/testfile
----i----------- /var/tmp/testfile
[tim@passepartout ~]$
但出于所有实际目的,执行
chattr(1)
可能要谨慎得多。作为一个子进程,而不是将上面的概念验证变成无需维护即 cocoa 靠运行的东西。
关于python-2.7 - 为什么 os.chflags() 在 Linux 下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176464/