本文介绍了如何在Python中使用os.umask()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用os模块设置umask.请注意,我在〜/.profile中设置的普通umask是umask 0027.

I'm trying to set a umask using the os module. Please note my normal umask set in my ~/.profile is umask 0027.

在bash外壳中,

umask 0022

将允许使用权限创建文件

will allow a file to be created with permissions

-rw-r--r--

但是,当我们导入os模块并执行以下操作时:

However, when us import the os module and do this:

os.umask(0022)
[do some other code here that creates a file]

我获得了

----------

首先,如何在外壳中使os.umask(mask)表现得像umask?

First, how do I make os.umask(mask) behave like umask in the shell?

第二,两者之间的区别是什么逻辑?

Second, what is the logic between the difference of the two?

注意:我尝试将0022转换为十进制,以防出现以下情况:

Note: I tried converting the 0022 to decimal in case it is expecting a decimal by doing:

os.umask(18)

但它授予了权限

-----w--w-

还请注意,我尝试过

os.umask(00022)

os.mask(0o0022)

哪一个也不起作用.

推荐答案

对umask的误解.umask设置默认的拒绝,而不是默认的权限.所以

Misunderstanding of umask, I think.The umask sets the default denials, not the default permissions.So

import os
oldmask = os.umask (0o22)
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)

确实应该产生如下文件:

should indeed produce files as follows:

-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删除组和其他组的写访问权限,这正是我们在此处看到的行为.我发现回到八进制数字表示的二进制文件会有所帮助:

The umask 022 removes write access for group and others, which is exactly the behaviour we see there.I find it helps to go back to the binary that the octal numbers represent:

 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

该程序的行为符合您的要求,不一定符合您的预期.常见的情况是,使用计算机:-)

The program is behaving as you asked it to, not necessarily as you thought it should. Common situation, that, with computers :-)

这篇关于如何在Python中使用os.umask()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 18:40