我想在可执行的python脚本中创建一个文件。
import os
import stat
os.chmod('somefile', stat.S_IEXEC)
看来os.chmod
没有像unix chmod
那样“添加”权限。在最后一行注释掉的情况下,该文件具有filemode -rw-r--r--
,未注释掉,文件模式为---x------
。如何在保持其余模式完好的同时添加u+x
标志?
使用os.stat()
获取当前权限,使用|
或位一起使用,并使用os.chmod()
设置更新的权限。
例:
import os
import stat
st = os.stat('somefile')
os.chmod('somefile', st.st_mode | stat.S_IEXEC)
对于生成可执行文件(例如脚本)的工具,以下代码可能会有所帮助:
def make_executable(path):
mode = os.stat(path).st_mode
mode |= (mode & 0o444) >> 2 # copy R bits to X
os.chmod(path, mode)
这使得它(或多或少)尊重创建文件时生效的umask
:只为可以读取的那些设置了可执行文件。
用法:
path = 'foo.sh'
with open(path, 'w') as f: # umask in effect when file is created
f.write('#!/bin/sh\n')
f.write('echo "hello world"\n')
make_executable(path)
如果您知道所需的权限,那么以下示例可能是保持简单的方法。
Python 2:
os.chmod("/somedir/somefile", 0775)
Python 3:
os.chmod("/somedir/somefile", 0o775)
兼容(八进制转换):
os.chmod("/somedir/somefile", 509)
你也可以这样做
>>> import os
>>> st = os.stat("hello.txt")
当前的文件列表
$ ls -l hello.txt
-rw-r--r-- 1 morrison staff 17 Jan 13 2014 hello.txt
现在这样做。
>>> os.chmod("hello.txt", st.st_mode | 0o111)
你会在终端看到这个。
ls -l hello.txt
-rwxr-xr-x 1 morrison staff 17 Jan 13 2014 hello.txt
您可以按位或使用0o111使所有可执行文件,0o222使所有可写,0o444使所有可读。
像umask
一样尊重chmod +x
man chmod
说,如果没有给出augo
,请参阅:
chmod +x mypath
然后使用a
,但使用umask
:
字母ugoa的组合控制用户对文件的访问权限将被更改:拥有它的用户(u),文件组中的其他用户(g),不在文件组中的其他用户(o),或全部用户(一)。如果没有给出这些效果,则效果就好像给出了(a),但是在umask中设置的位不受影响。
这是一个完全模拟该行为的版本:
#!/usr/bin/env python3
import os
import stat
def get_umask():
umask = os.umask(0)
os.umask(umask)
return umask
def chmod_plus_x(path):
os.chmod(
path,
os.stat(path).st_mode |
(
(
stat.S_IXUSR |
stat.S_IXGRP |
stat.S_IXOTH
)
& ~get_umask()
)
)
chmod_plus_x('.gitignore')
另见:How can I get the default file permissions in Python?
在Ubuntu 16.04,Python 3.5.2中测试。
在python3中:
import os
os.chmod("somefile", 0o664)
请记住添加0o
前缀,因为权限设置为八进制整数,Python会自动将前导零的任何整数视为八进制。否则,你确实通过了os.chmod("somefile", 1230)
,这是664
的八进制。