2019年6月22日 / 381次阅读 / Last Modified 2019年8月7日
os模块
Python os模块提供的chmod()函数,对应的功能就是Linux系统的chmod程序。os.chmod()函数用来在Python代码中改变文件的访问权限。
先看一下这个函数的docstring吧:
>>> help(os.chmod)
Help on built-in function chmod in module posix:
chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Change the access permissions of a file.
path
Path to be modified. May always be specified as a str or bytes.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
mode
Operating-system mode bitfield.
dir_fd
If not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that
directory.
follow_symlinks
If False, and the last element of the path is a symbolic link,
chmod will modify the symbolic link itself instead of the file
the link points to.
It is an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
dir_fd and follow_symlinks may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
os.chmod函数参数定义中的*符号是什么意思?请参考:函数参数定义中独立的*符号,什么意思?
使用os.chmod()函数,需要用到stat模块提供的一组权限标志位,对应的就是函数mode参数(参见上面的docstring)。具体如下:
stat.S_ISUID, set uid bit,给程序设置SetUID权限的bit位。(关于SetUID权限,请参考:什么是SetUID权限?)
stat.S_ISGID, set group id bit,给程序文件设置SetGId权限的bit位。(关于SetGID权限,请参考:什么是SetGID权限?)
stat.S_ISVTX, Sticky bit. 当这个bit位设置到一个目录上时,它表示,这个目录中的文件和子目录,只能被owner或者root进行重命名或者删除,或者是授权的进程。这样能够保护在某些公用的目录中,自己的文件不会被其它用户误删除。
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, 其它组成员的执行权限
stat.S_ENFMT, System V file locking enforcement.
stat.S_IREAD, Unix V7 synonym for S_IRUSR
stat.S_IWRITE, Unix V7 synonym for S_IWUSR
stat.S_IEXEC, Unix V7 synonym for S_IXUSR
>>> from stat import *
>>> import os
>>> os.listdir()
['test.txt']
>>> filemode(os.stat('test.txt').st_mode)
'-rwx------'
>>> os.chmod('test.txt', 0)
>>> filemode(os.stat('test.txt').st_mode)
'----------'
>>> os.chmod('test.txt', S_IRWXU | S_IRWXG | S_IRWXO)
>>> filemode(os.stat('test.txt').st_mode)
'-rwxrwxrwx'
注意stat模块的引入方式,filemode函数是stat模块提供的接口。
-- EOF --
本文链接:https://www.pynote.net/archives/275
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记