3

My python script creates a file if it doesn't exist, reads and writes that file. The script may be run by root (automated) or by the user (refresh request). I need the file to be created with write permission so that in both cases the file can be re-written.

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

but then...

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

However, this script works and I don't understand the difference:

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

...and then:

$ ls -l
-rwxrwxrwx 1 pi pi  0 Feb 22 13:54 file
pinhead
  • 907
  • 2
  • 10
  • 14

1 Answers1

5

You're not setting umask, you're setting the file mode bits, which are masked by the 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. ...

Your umask value appears to be 0022, thus masking out group and other user write permissions.

This

os.fchmod(f, 0777)

explicitly sets the file permissions to 0777 despite the umask value.

Andrew Henle
  • 27,654
  • 3
  • 23
  • 49
  • ahhhhh ok thanks, so in the one-liner what should the third argument be if I always want to create a file with 777? – pinhead Feb 22 '16 at 22:06
  • @pinhead - Either that or explicitly set `umask` to zero. Note that setting `umask` will impact everything you do in your process. That's not a big deal if you're running single-threaded because you can set `umask` back, but in a multithreaded application it can be. – Andrew Henle Feb 22 '16 at 22:07
  • @pinhead, there's no way to do that as a one-liner unless you're running in an environment with umask 000 (which is dangerous) – BingsF Feb 22 '16 at 22:07