Python os.chmod() 方法将 path 模式更改为指定的数字模式。该模式可以采用以下值之一或它们的按位 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 os.chmod() 方法的语法 -
os.chmod(path, mode);
参数
- path − 这是将为其设置模式的路径。
- mode − 这可能采用上述值之一或它们的按位 OR 组合。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.chmod() 方法的用法。在这里,我们首先通过传递 stat 将文件设置为仅由组执行。S_IXGRP 作为方法的 mode 参数。然后我们传递统计数据。S_IWOTH 作为方法的 mode 参数。这指定文件只能由其他人写入。
import os, sys, stat
# Assuming /tmp/foo.txt exists, Set a file execute by the group.
os.chmod("/tmp/foo.txt", stat.S_IXGRP)
# Set a file write by others.
os.chmod("/tmp/foo.txt", stat.S_IWOTH)
print ("Changed mode successfully!!")
当我们运行上述程序时,它会产生以下结果——
Changed mode successfully!!
示例 2
在这里,我们首先将文件设置为仅由组写入。这是通过传递 stat 来完成的。S_IWGRP 作为方法的 mode 参数。然后我们传递统计数据。S_IXGRP 作为方法的 mode 参数。这指定文件只能由组执行。
# importing the libraries
import os
import sys
import stat
# Setting the given file written by the group.
os.chmod("Code.txt", stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.chmod("Code.txt", 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.chmod() 方法时,我们在设置权限之前写 0o。它表示一个八进制整数。文件权限设置为 755,即 owner 可以读、写、搜索;others 和 group 只能在文件中搜索。
import os
file = "code.txt"
os.chmod(file, 0o755)
stat = os.stat(file)
mode = oct(stat.st_mode)[-4:]
print('The mode is:',mode)
以下是上述代码的输出 -
The mode is: 0666