Python os.fchmod() 方法将文件的模式更改为指定的数字模式。该模式可以采用以下值之一或它们的按位 OR 组合 -
- stat.S_ISUID − 在执行时设置用户 ID。
- stat.S_ISGID − 在执行时设置组 ID。
- stat.S_ENFMT − 强制记录锁定。
- stat.S_ISVTX − 执行后保存文本图像。
- stat.S_IREAD − 由所有者读取。
- stat.S_IWRITE − 由所有者写入。
- stat.S_IEXEC − 按所有者执行。
- stat.S_IRWXU - 按所有者读取、写入和执行。
- stat.S_IRUSR − 由所有者读取。
- stat.S_IWUSR − 由所有者写入。
- stat.S_IXUSR − 按所有者执行。
- stat.S_IRWXG - 按组读取、写入和执行。
- stat.S_IRGRP − 按组读取。
- stat.S_IWGRP − 按组写入。
- stat.S_IXGRP − 按组执行。
- stat.S_IRWXO - 由其他人读取、写入和执行。
- stat.S_IROTH − 被其他人阅读。
- stat.S_IWOTH − 由他人撰写。
- stat.S_IXOTH − 由他人执行。
注意 − 此方法在 Python 2.6 及更高版本中可用。并且仅在 UNIX/LINUX 平台中可用。
语法
以下是 Python os.fchmod() 方法的语法 -
os.fchmod(fd, mode);
参数
- fd − 这是将要设置模式的文件描述符。
- mode − 这可能采用上述值之一或它们的按位 OR 组合。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.fchmod() 方法的用法。在这里,我们首先通过传递 stat 将文件设置为仅由组执行。S_IXGRP 作为方法的 mode 参数。然后我们传递统计数据。S_IWOTH 作为方法的 mode 参数。这指定文件只能由其他人写入 -
import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set a file execute by the group.
os.fchmod( fd, stat.S_IXGRP)
# Set a file write by others.
os.fchmod(fd, stat.S_IWOTH)
print ("Changed mode successfully!!")
# Close opened file.
os.close(fd)
当我们运行上述程序时,它会产生以下结果——
Changed mode successfully!!
示例 2
在这里,我们首先将文件设置为仅由组写入。这是通过传递 stat 来完成的。S_IWGRP 作为方法的 mode 参数。然后我们传递统计数据。S_IXGRP 作为方法的 mode 参数。这指定文件只能由组执行。
# importing the libraries
import os
import sys
import stat
# Now open a file "code.txt"
filedesc = os.open("code.txt", os.O_RDONLY )
# Setting the given file written by the group.
os.fchmod(filedesc, stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.fchmod(filedesc, stat.S_IXGRP)
print("Now the file can only be executed by the group.")
在执行上述代码时,我们得到以下输出 -
This file can only be written by the group
Now the file can only be executed by the group.
Now the file can only be executed by the group.
示例 3
在这里,当我们使用 os.fchmod() 方法时,我们在设置权限之前编写 0o。它表示一个八进制整数。文件权限设置为 755,即 owner 可以读、写、搜索;others 和 group 只能在文件中搜索。
import os
import stat
file = "code.txt"
filedesc = os.open("code.txt", os.O_RDONLY )
mode = 0o755
os.fchmod(filedesc,mode)
stat = os.stat(file)
mode = oct(stat.st_mode)[-4:]
print('The mode is:',mode)
以下是上述代码的输出 -
The mode is: 0755