使用python

时间:2015-12-17 15:28:00

标签: python file-permissions chmod shlex

这是我的设置:

我有一个VirtualMachine(Ubuntu 14.04.LTS),其中运行PostgreSQL / PostGIS数据库。

使用QGIS中的Windows 7,我连接到此数据库并将要素图层加载到我的GIS项目中。

使用一些python代码,我创建了一个带有tile ID和一些信息的文件。

import os
import io
import time

layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
if lyr.name() == "fishnet_final":
    layer = lyr

for f in layer.selectedFeatures():
    pth = os.path.join(os.path.dirname(r'H:\path_to_file\'), str(f['name']) + "_" + str(time.strftime("%Y-%m-%d")) + "_" + str(f['country']) + ".txt")
    fle = open(pth,'wb')    
    fle.writelines(str(f['name']))
    fle.write('\n')
    fle.write(str(time.strftime("%Y-%d-%m")))
    fle.write('\n')
    fle.write(str(f['country']))
    fle.write('\n')
    fle.close()
    os.rename(pth, pth.replace(' ', ''))

该文件具有以下权限:

-rwx------

我想为我的群组和其他人设置相同的权限。

-rwxrwxrwx

我试过了:

import shlex
command=shlex.split("chmod 777 r'H:\path_to_file\file.txt'") 
subprocess.call(command)

没有成功。

工作原理是:

command=shlex.split("touch r'H:\path_to_file\file.txt'")

OR

command=shlex.split("rm r'H:\path_to_file\file.txt'")

为什么chmod命令不起作用?

在UNIX下我可以chmod这个文件,我和Windows中的用户一样。

我也尝试过os.chmod方法。但没有成功。

import os, stat
st = os.stat(r'H:\path_to_file\file.txt')
os.chmod(r'H:\path_to_file\file.txt', st.st_mode | 0o111 )

更新

当我在UNIX(Solaris)下执行“chmod 777文件”时,权限为

-rwxrwxrwx

我现在可以做的是在GIS项目中降级/删除Windows下的权限:

subprocess.call(r'chmod 400 "H:\path_to_file\file.txt"', shell=True)
0
-r-xr-xr-x

使用此命令,我在python控制台输出中得到0反馈

当我在新文件上执行chmod 777时,我也收到了0反馈,但没有任何反应。

问题是我只能降级权限。我无法设置新权限!

3 个答案:

答案 0 :(得分:5)

来自os module documentation

  

注意:尽管Windows支持chmod(),但您只能使用它设置文件的只读标志(通过stat.S_IWRITE和stat.S_IREAD常量或相应的整数值)。 忽略所有其他位。

对于Windows权限,您可以管理ACL。从another answer进行调整,您需要pywin32库:

cd /d C:\Program Files (x86)\Notepad++\updater
gup -options

import win32security import ntsecuritycon as con FILENAME = r"H:\path_to_file\file.txt" user, domain, type = win32security.LookupAccountName ("", "Your Username") sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL() dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user) sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd) 标志更改为您需要的标志。

答案 1 :(得分:3)

shell命令中r字符的意图是什么?你的意思是把它放在整个弦的前面吗? 您是否检查过触摸生成了哪个文件?

当我尝试您的示例时,它运行此命令:angular.module("myfapp", []).controller("HelloController", ["$scope", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }]) .controller('MainCtrl', ["$scope", function($scope) { }]) .directive('validNumber', function() { return { restrict: "A", require: '?ngModel', link: function(scope, element, attrs, ngModelCtrl) { if (!ngModelCtrl) { return; } ngModelCtrl.$parsers.push(function(val) { if (val === null) return; var myRegex = /\d+\.(\d{1,2})?/; var clean = myRegex.exec(val)[0]; if (val != clean) { ngModelCtrl.$setViewValue(clean); ngModelCtrl.$render(); } return clean; }); element.bind('keypress', function(event) { if (event.keyCode === 32) { event.preventDefault(); } }); } }; }); ,即创建文件<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script> <script src="script.js"></script> <style> .entry { width: 300px; margin: 10px auto; text-align: center; } </style> </head> <body ng-app="myfapp"> <div ng-controller="HelloController" > <h2 class="entry">Welcome {{ helloTo.title }} to the world of Tutorialspoint!</h2> </div> <section ng-controller="MainCtrl"> <h4 class="entry">AngularJS Numeric Value Widget</h4> <div class="well entry"> <label>Employee Age <input type="text" ng-model="employee.age" placeholder="Enter an age" valid-number/> </label> <div> {{ employee.age }} </div> </div> </section> </body> </html>

这对我来说很好用:

['touch', 'rH:\\path_to_file\x0cile.txt']

答案 2 :(得分:2)

试试这个(我现在没有Linux机器来测试它):

import subprocess
subprocess.call(r'chmod 777 "H:\path_to_file\file.txt"', shell=True)

如果文件名是用户提供的,出于安全原因,应避免使用shell=True。你可以尝试:

filename = r"H:\path_to_file\file.txt"
subprocess.call(['chmod','777',filename])