python - 如何在 Python 中使用 os.umask()

标签 python linux umask

我正在尝试使用 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/

相关文章:

python - 波浪号登录 Pandas 数据框

python - 如何获得 Python Selenium 中的最后一个类

PHP ssh2_sftp_mkdir 创建权限错误

java - 如何从Java获取当前的umask值?

python - 在 __init__.py 中递归填充 __all__

python - Numpy中的均方误差?

linux - 内核中特定于进程的数据

linux - 运行 RabbitMQ 的 CentOS 无法创建跟踪文件并远程登录其他 vhost

linux - 计算文件中 2 个字符串之间匹配的行数

python - 为什么 python 中的 os.mkdir 设置权限的方式与 bash 中的 mkdir 之一不同?