I'm trying to set a umask using the os module. Please note my normal umask set in my ~/.profile is umask 0027.
In a bash shell,
umask 0022
will allow a file to be created with permissions
-rw-r--r--
However, when us import the os module and do this:
os.umask(0022)
[do some other code here that creates a file]
I get permissions of
----------
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?
Note: I tried converting the 0022 to decimal in case it is expecting a decimal by doing:
os.umask(18)
but it gave permissions of
-----w--w-
Also note, I tried
os.umask(00022)
and
os.mask(0o0022)
Which didn't work either.
Misunderstanding of umask, I think. The umask sets the default denials, not the default permissions. So
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)
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
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 :-)