Can I set the umask for tempfile.NamedTemporaryFil

2020-03-01 09:31发布

In Python (tried this in 2.7 and below) it looks like a file created using tempfile.NamedTemporaryFile doesn't seem to obey the umask directive:

import os, tempfile
os.umask(022)
f1 = open ("goodfile", "w")
f2 = tempfile.NamedTemporaryFile(dir='.')
f2.name

Out[33]: '/Users/foo/tmp4zK9Fe'

ls -l
-rw-------  1 foo  foo  0 May 10 13:29 /Users/foo/tmp4zK9Fe
-rw-r--r--  1 foo  foo  0 May 10 13:28 /Users/foo/goodfile

Any idea why NamedTemporaryFile won't pick up the umask? Is there any way to do this during file creation?

I can always workaround this with os.chmod(), but I was hoping for something that did the right thing during file creation.

2条回答
放荡不羁爱自由
2楼-- · 2020-03-01 10:08

This is a security feature. The NamedTemporaryFile is always created with mode 0600, hardcoded at tempfile.py, line 235, because it is private to your process until you open it up with chmod. There is no constructor argument to change this behavior.

查看更多
Luminary・发光体
3楼-- · 2020-03-01 10:11

In case it might help someone, I wanted to do more or less the same thing, here is the code I have used:

import os
from tempfile import NamedTemporaryFile

def UmaskNamedTemporaryFile(*args, **kargs):
    fdesc = NamedTemporaryFile(*args, **kargs)
    umask = os.umask(0)
    os.umask(umask)
    os.chmod(fdesc.name, 0o666 & ~umask)
    return fdesc
查看更多
登录 后发表回答