出现 OSError: [Errno 13] 权限被拒绝: <目录名称>, os.walk 退出
我有一个脚本,可以告诉我一个文件夹里所有的文件,这样用户就需要把它们删掉(这个集群管理得很糟糕,没有真正的超级用户)。
当我运行这个脚本时,出现了这样的错误:
OSError: [Errno 13] 权限被拒绝: '
ls: : 权限被拒绝
我不能写出文件夹的名字(因为公司政策)。
代码如下:
#!/depot/Python-3.1.1/bin/python3.1
from stat import *
import stat
import sys
from collections import defaultdict
from pwd import getpwuid
import sys
sys.path.append('/remote/us01home15/ldagan/python')
import mailer
import os
import re
import glob
import subprocess
import pwd
def find_owner(file):
return pwd.getpwuid(os.stat(file)[stat.ST_UID]).pw_name
if (len(sys.argv) < 1):
sys.error('''Please input <runda number> <case number>''')
files_by_users=defaultdict(list)
runda_num="".join(sys.argv[1])
dir_basic='/berry/secure'
case_num="".join(sys.argv[2])
secure_dir="".join([dir_basic,"/"])
i=1
dirs=[]
runda_case_dir="".join([dir_basic,'/',runda_num,'/',case_num ])
while (os.path.exists(secure_dir)):
if (os.path.exists(runda_case_dir)):
dirs.append(runda_case_dir)
i+=1
secure_dir="".join([dir_basic,str(i)])
runda_dir="/".join([secure_dir,runda_num,case_num])
#now finding list of
manager_email='ldagan@synopsys.com zafrany@synopsys.com'
def bull (msg):
i=1
for dir in dirs:
for root,dirs,files in os.walk(dir,onerror=bull):
for file in files:
file_full_name=os.path.join(root,file)
files_by_users[find_owner(file_full_name)].append(file_full_name)
for username in files_by_users:
sendOffendingNotice(username, file_by+users[username], manager_email)
def sendOffendingNotice(username,filenames,managerEmail):
"""gets file name & manager Email
sends an Email to the manager for review. As there are no smtp
definitions, mailx shall be used"""
user_email=username+'@synopsys.com'
message="""The following files \n""" + """\n""".join(filenames) +"""\n""" + \
""" which belongs to user """ + username +""" does not meet the required names's SPEC\nPlease keep it under a directory which has a proper case/star name\n"""
message= """echo \"""" + message+ """" | mailx -s "Offending files" """ + managerEmail +" " #+user_email
process=subprocess.Popen(message,shell=True)
这个脚本没有发送邮件,而是直接停止了运行。
谢谢你们帮助一个新手。
1 个回答
2
听起来你的脚本是以普通用户的身份运行的,所以没有权限去读取某个文件夹。
如果能看到完整的错误信息会更有帮助(即使路径名被更改了),因为这样我们就能知道错误发生在哪一行。
基本上,解决办法是用一个try...except块来捕捉这个错误:
try:
# Put the line that causes the exception here
# Do not trap more lines than you need to.
...
except OSError as err:
# handle error (see below)
print(err)
特别是考虑到S.Lott的评论,要注意那些导致操作系统错误的文件或文件夹,可能正是你需要给其所有者发送邮件的文件。不过,为了能够读取这些文件夹,你的脚本可能需要以超级用户(或更高权限)的身份运行。