![](/img/trans.png)
[英]Can you GPU accelerate a simple math equation in python such as: y = 1/x and how do you do it?
[英]How do you do a simple "chmod +x" from within python?
我想從可執行的 python 腳本中創建一個文件。
import os
import stat
os.chmod('somefile', stat.S_IEXEC)
看起來os.chmod
不像 unix chmod
那樣“添加”權限。 注釋掉最后一行后,文件的文件模式為-rw-r--r--
,未注釋掉的文件模式為---x------
。 如何在保持模式的 rest 不變的同時添加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)
如果您知道所需的權限,那么以下示例可能是保持簡單的方法。
蟒蛇2:
os.chmod("/somedir/somefile", 0775)
蟒蛇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 使所有可讀。
像chmod +x
一樣尊重umask
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')
另請參閱: 如何在 Python 中獲得默認文件權限?
在 Ubuntu 16.04、Python 3.5.2 中測試。
是否有理由不讓操作系統進行提升? 就像是:
導入子流程
subprocess.call(chmod +x file.py)
我們可以使用os.system()
在 python 中直接調用chmod +x
命令
import os
os.system("chmod +x somefile")
這將打開文件的所有可執行位:
os.chmod("path", os.stat("path").st_mode | 0o111)
在python3中:
import os
os.chmod("somefile", 0o664)
請記住添加0o
前綴,因為權限設置為八進制整數,Python 會自動將任何前導零的整數視為八進制。 否則,您確實在傳遞os.chmod("somefile", 1230)
,它是664
八進制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.