How to use os.umask() in Python

后端 未结 4 1258
说谎
说谎 2020-12-31 07:34

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
         


        
4条回答
  •  一生所求
    2020-12-31 08:27

    You'll probably need to show us the code that constitutes:

    [do some other code here that creates a file]
    

    The code you have works fine on my system:

    import os
    oldmask = os.umask (022)
    fh1 = os.open ("qq1.junk", os.O_CREAT, 0777)
    fh2 = os.open ("qq2.junk", os.O_CREAT, 0022)
    os.umask (oldmask)
    os.close (fh1)
    os.close (fh2)
    

    producing 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
    

    You should also note the restoration of the old umask value which minimises the impact of changing it to the local operation.

    As you can see from the results above, you also need to be aware that the umask value is "subtracted" from the mode you're using to create the file and we don't know what that mode is in your particular case.

    That's evident even in your bash sample since a umask value of 022 when creating a file of mode 777 would result in r-xr-xr-x, not rw-r--r-- as you have it.


    Based on your comments below where you indicate you're using open rather than os.open, a cursory glance of the Python source seems to indicate that this translates to a C fopen call which uses 0666 as the initial mode. This is supported by the slightly modified code:

    import os
    oldmask = os.umask (022)
    fh3 = open ("qq3.junk", "w")
    os.umask (0)
    fh4 = open ("qq4.junk", "w")
    os.umask (oldmask)
    fh3.close()
    fh4.close()
    

    which gives us:

    -rw-r--r-- 1 pax pax 0 Apr 24 11:44 qq3.junk
    -rw-rw-rw- 1 pax pax 0 Apr 24 11:44 qq4.junk
    

    So I'm not entirely certain why you're getting 0000 permissions in your case.

    It would be worth seeing what the results are when you run that above program in your environment. If it's the same as I get then the problem may well lie somewhere else.

提交回复
热议问题