如何获得Python中的默认文件权限? [英] How can I get the default file permissions in Python?
问题描述
我正在编写一个Python脚本,在该脚本中,我将输出写入一个临时文件,然后在完成并关闭该文件后将其移至其最终目的地.脚本完成后,我希望输出文件具有与通常通过open(filename,"w")
创建的文件相同的权限.照原样,该文件将具有tempfile模块用于临时文件的限制性权限集.
I am writing a Python script in which I write output to a temporary file and then move that file to its final destination once it is finished and closed. When the script finishes, I want the output file to have the same permissions as if it had been created normally through open(filename,"w")
. As it is, the file will have the restrictive set of permissions used by the tempfile module for temp files.
如果我在原地创建了输出文件,是否可以通过某种方式弄清楚输出文件的默认"文件权限是什么,以便在移动之前将其应用于临时文件?
Is there a way for me to figure out what the "default" file permissions for the output file would be if I created it in place, so that I can apply them to the temp file before moving it?
推荐答案
出于记录,我遇到了类似的问题,这是我使用的代码:
For the record, I had a similar issue, here is the code I have used:
import os
from tempfile import NamedTemporaryFile
def UmaskNamedTemporaryFile(*args, **kargs):
fdesc = NamedTemporaryFile(*args, **kargs)
# we need to set umask to get its current value. As noted
# by Florian Brucker (comment), this is a potential security
# issue, as it affects all the threads. Considering that it is
# less a problem to create a file with permissions 000 than 666,
# we use 666 as the umask temporary value.
umask = os.umask(0o666)
os.umask(umask)
os.chmod(fdesc.name, 0o666 & ~umask)
return fdesc
这篇关于如何获得Python中的默认文件权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!