我正在尝试使用 os 模块设置一个 umask。请注意我在 ~/.profile 中设置的正常 umask 是 umask 0027。
在 bash shell 中,
umask 0022
将允许创建具有权限的文件
-rw-r--r--
但是,当我们导入 os 模块并执行此操作时:
os.umask(0022)
[do some other code here that creates a file]
我得到了
的权限----------
首先,如何让 os.umask(mask) 在 shell 中表现得像 umask?
其次,两者区别的逻辑是什么?
注意:我尝试将 0022 转换为十进制,以防它需要一个小数:
os.umask(18)
但是它给了权限
-----w--w-
另请注意,我试过了
os.umask(00022)
和
os.mask(0o0022)
这也不起作用。
最佳答案
对umask的误解,我想。 umask 设置默认的拒绝,而不是默认的权限。 所以
import os
oldmask = os.umask (0o022)
fh1 = os.open ("qq1.junk", os.O_CREAT, 0o777)
fh2 = os.open ("qq2.junk", os.O_CREAT, 0o022)
os.umask (oldmask)
os.close (fh1)
os.close (fh2)
确实应该生成如下文件:
-rwxr-xr-x 1 pax pax 0 Apr 24 11:11 qq1.junk
---------- 1 pax pax 0 Apr 24 11:11 qq2.junk
umask 022 删除组和其他人的写访问权限,这正是我们在那里看到的行为。 我发现回到八进制数表示的二进制会有所帮助:
usr grp others
-rwx rwx rwx is represented in octal as 0777, requested for qq1.junk
-000 010 010 umask of 022 removes any permission where there is a 1
-rwx r-x r-x is the result achieved requesting 0777 with umask of 022
---- -w- -w- is represented in octal as 0022, requested for qq2.junk
-000 010 010 umask of 022 removes any permission where there is a 1
---- --- --- is the result achieved requesting 0022 with umask of 022
程序按照您的要求运行,不一定按照您的预期运行。常见的情况是,对于计算机 :-)
关于python - 如何在 Python 中使用 os.umask(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291131/