2012-10-09 35 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) –

相關問題