你如何在python中做一个简单的“chmod + x”?
我想在可执行的python脚本中创建一个文件。
import os
import stat
os.chmod('somefile', stat.S_IEXEC)
看来os.chmod
没有像unix chmod
那样'添加'权限。 在最后一行注释掉的情况下,该文件的文件模式为-rw-r--r--
,未注释掉,文件模式为---x------
。如何在保持其余模式完整的同时添加u+x
标志?
priestc asked 2019-07-27T12:15:28Z
6个解决方案
155 votes
使用os.stat()
获取当前权限,使用|
或位,并使用os.chmod()
设置更新的权限。
例:
import os
import stat
st = os.stat('somefile')
os.chmod('somefile', st.st_mode | stat.S_IEXEC)
16 votes
对于生成可执行文件(例如脚本)的工具,以下代码可能会有所帮助:
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)
6 votes
如果您知道所需的权限,那么以下示例可能是保持简单的方法。
Python 2:
os.chmod("/somedir/somefile", 0775)
Python 3:
os.chmod("/somedir/somefile", 0o775)
兼容(八进制转换):
os.chmod("/somedir/somefile", 509)
引用权限示例
2 votes
你也可以这样做
>>> 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使所有可读。
0 votes
尊重a
,如umask
a
说如果没有给出umask
,如:
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')
另请参阅:如何在Python中获取默认文件权限?
在Ubuntu 16.04,Python 3.5.2中测试。
0 votes
在python3中:
import os
os.chmod("somefile", 0o664)
请记住添加0o
前缀,因为权限设置为八进制整数,Python会自动将前导零的任何整数视为八进制。 否则,您确实通过了os.chmod("somefile", 1230)
,这是664
的八进制。