2012-10-09 284 views
79

我想从可执行的python脚本中创建一个文件。你如何在python中做一个简单的“chmod + x”?

import os 
import stat 
os.chmod('somefile', stat.S_IEXEC) 

看来os.chmod没有 '添加' 权限的方式UNIX chmod一样。将最后一行注释掉后,文件的文件模式为-rw-r--r--,未注释掉,文件模式为---x------。我怎样才能添加u+x标志,同时保持其余模式不变?

回答

133

使用os.stat()获取当前权限,使用|或位合并,并使用os.chmod()设置更新的权限。

例子:

import os 
import stat 

st = os.stat('somefile') 
os.chmod('somefile', st.st_mode | stat.S_IEXEC) 
+2

这只使得它可执行由美国呃。海报问的是“chmod + x”,这使得它可以在整个板上执行(用户,组,世界) –

+26

使用以下命令使其可以被所有人执行... stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH。注意:该值与八进制0111相同,因此您可以执行st.st_mode | 0111 –

+0

[我的回答如下](http:// stackoverflow。com/a/30463972/119527)将R位拷贝到X,正如人们所期望的那样,编译器。 –

12

对于生成的可执行文件(例如脚本)的工具,下面的代码可能会有所帮助:

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) 
+2

在Python 3中更改了八进制文字。而不是'0444',您可以使用'0o444'。或者,如果你想同时支持,只需写'292'。 – Kevin

+1

@Kevin它[貌似](https://docs.python.org/3.0/whatsnew/3.0.html#new-syntax)Python 2.6支持新的语法,所以使用它似乎是合理的。 (对于兼容性参考点,CentOS 6随附Python 2.6)。 –

+2

我不知道Python 3已经删除了传统的八进制文字。非常感谢你的帮忙。 –

2

你也可以做到这一点

>>> 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让所有可读。

3

如果你知道你想要的权限,那么下面的例子可能是保持它简单的方法。

的Python 2:

os.chmod("/somedir/somefile", 0775) 

的Python 3:

os.chmod("/somedir/somefile", 0o775) 

与(八进制转换)兼容:

os.chmod("/somedir/somefile", 509) 

参考permissions examples

+4

这应该是os.chmod(“/ somedir/somefile”,0o775) –

相关问题