你如何做一个简单的“chmod + x”从python内?
我想从一个可执行的python脚本中创build一个文件。
import os import stat os.chmod('somefile', stat.S_IEXEC)  它看起来os.chmod没有“添加”权限的方式unix chmod做的。 最后一行注释掉了,文件的文件模式是-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) 
 这使得它(或多或less)尊重创build文件时生效的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) 
如果你知道你想要的权限,那么下面的例子可能是保持简单的方法。
os.chmod(“/ somedir / somefile”,0775)
引用权限示例
你也可以做到这一点
 >>> 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) 
你会在terminal看到这个
 ls -l hello.txt -rwxr-xr-x 1 morrison staff 17 Jan 13 2014 hello.txt 
你可以按位或0o111使所有可执行文件,0222使所有可写,0444使所有可读。