Python os.open() 无法将 umask 设置为 777(最大 755)

Python os.open() can not set umask to 777 (755 max)

我的 python 脚本创建一个文件(如果不存在),读取并写入该文件。该脚本可能由 root(自动)或用户(刷新请求)运行。我需要创建具有写入权限的文件,以便在这两种情况下都可以重写文件。

import os
f = os.open('file', os.O_CREAT, 0777)
os.close(f)

但是然后...

$ ls -l
-rwxr-xr-x 1 pi pi  0 Feb 22 13:51 file

但是,这个脚本有效,我不明白其中的区别:

import os  
f = os.open('file', os.O_CREAT)
os.fchmod(f, 0777)
os.close(f)

...然后:

$ ls -l
-rwxrwxrwx 1 pi pi  0 Feb 22 13:54 file

您没有设置 umask,您设置的是文件模式位,它们被 umask屏蔽Per the documentation:

Open the file file and set various flags according to flags and possibly its mode according to mode. The default mode is 0777 (octal), and the current umask value is first masked out. ...

您的 umask 值似乎是 0022,因此屏蔽了组和其他用户的写入权限。

这个

os.fchmod(f, 0777)

尽管值为 umask,但明确将文件权限设置为 0777