我正在學習編寫用於工作的Python腳本,並遇到一些問題。該腳本應該讀取一個文件,並將權限打印到電子郵件。我的問題是,當它嘗試調用permission()方法時出現錯誤,並且我不知道如何解決該問題。權限,Python腳本
Python代碼
import smtplib
import os
import stat
result = ""
def permission(file):
s = os.stat(file)
mode = s.st_mode
if(stat.S_IRUSR & mode):
ownerRead = 1
result += ownerRead
else:
ownerRead = 0
result += ownerRead
if(stat.S_IWUSR & mode):
ownerWrite = 1
result += ownerWrite
else:
ownerWrite = 0
result += ownerWrite
if(stat.S_IXUSR & mode):
ownerExecute = 1
result += ownerExecute
else:
ownerExecute = 0
result += ownerExecute
if(stat.S_IRGRP & mode):
groupRead = 1
result += groupRead
else:
groupRead = 0
result += groupRead
if(stat.S_IWGRP & mode):
groupWrite = 1
result += groupWrite
else:
groupWrite = 0
result += groupWrite
if(stat.S_IXGRP & mode):
groupExecute = 1
result += groupExecute
else:
groupExecute = 0
result += groupExecute
if(stat.S_IROTH & mode):
otherRead = 1
result += otherRead
else:
otherRead = 0
result += otherRead
if(stat.S_IWOTH & mode):
otherWrite = 1
result += otherWrite
else:
otherWrite = 0
result += otherWrite
if(stat.S_IXOTH & mode):
otherExecute = 1
result += otherExecute
else:
otherExecute = 0
result += otherExecute
return result
to = '[email protected]'
gmail_user = '[email protected]'
gmail_pwd = 'pwd'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:permissions \n'
print header
values = permission(file)
print values
msg = header + values
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()
錯誤輸出
Traceback (most recent call last):
File "lastpart.py", line 83, in <module>
values = permission(file)
File "lastpart.py", line 15, in permission
s = os.stat(file)
TypeError: coercing to Unicode: need string or buffer, type found
嘗試重命名你的函數的參數? 'file'已經是一個類型名稱,顯然,python也會因爲使用'file'參數而變得困惑。 – 2012-02-15 06:52:32
@Ulrich:不,Python可以讓它們保持直線。但提問者不能。 – 2012-02-15 06:54:58