除了我問here的問題之外,我堅持要排除錯誤異常。 我已經整理出從另一個文件中讀取文件的列表,但如果其中一個引用的文件不存在,我正在努力。 我希望能夠識別錯誤,發送電子郵件,然後創建文件供以後使用。 但是,我收到的「嘗試,除了其他」塊的縮進錯誤,我投入。 它看起來應該工作,但我不能讓它運行! Gah!幫幫我!!!嘗試上的縮進錯誤,除了Python中的其他塊以外
日誌文本文件包含以下內容:
//server-1/data/instances/devapp/log/audit.log
//服務器/數據/實例/ devapp /日誌/bizman.db.log
//server-1/data/instances/devapp/log/foo.txt #此文件不服務器
我的代碼如下所示的存在。我認爲最好把它整個發佈而不是一個片段,以防它在程序的早期階段被篡改!
import os, datetime, smtplib
today = datetime.datetime.now().strftime('%Y-%m-%d')
time_a = datetime.datetime.now().strftime('%Y%m%d %H-%M-%S')
checkdir = '/cygdrive/c/bob/python_'+ datetime.datetime.now().strftime('%Y-%m-%d')+'_test'
logdir = '/cygdrive/c/bob/logs.txt'
errors = '/cygdrive/c/bob/errors.txt'
#email stuff
sender = '[email protected]'
receivers = '[email protected]'
message_1 = """From: errors <[email protected]>
To: Bob <[email protected]>
Subject: Log file not found on server
A log file has not been found for the automated check.
The file has now been created.
"""
#end of email stuff
try:
os.chdir (checkdir) # Try opening the recording log directory
except (OSError, IOError), e: # If it fails then :
os.mkdir (checkdir) # Make the new directory
os.chdir (checkdir) # Change to the new directory
log = open ('test_log.txt', 'a+w') #Create and open log file
else :
log = open ('test_log.txt', 'a+w') #Open log file
log.write ("***starting file check at %s ***\r\n\r\n"%tme_a)
def log_opener (logdir) :
with open(logdir) as log_lines: #open the file with the log paths in
for line in log_lines: # for each log path do :
timestamp = time_a + (' Checking ') + line + ('\r\n')
try:
with open(line.strip()) as logs:
except (OSError,IOError), e:
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
log.write (timestamp)
log.write ("Log file not found. Email sent. New file created.")
except SMTPException:
log.write (timestamp)
log.write ("Log file not found. Unable to send email. New file created.")
else : # The following is just to see if there is any output... More stuff to be added here!
print line + ('\r\n')
log.write (timestamp)
print "".join(logs.readlines())
print log_opener(logdir)
我得到的錯誤如下:
$ python log_5.py
File "log_5.py", line 38
except (OSError,IOError), e:
^
IndentationError: expected an indented block
據我所知道的,它應該工作,但...
作爲一個額外的說明,我已經沒有長時間的學習,所以我的很多代碼都是從各種教程修改而來,或者從這裏或網絡上的其他地方借用。 我可能在這裏犯了一個非常基本的錯誤,所以請耐心等待我!
非常感謝您的幫助!
顯然,您的縮進在第一次嘗試/除了和函數中的縮進之間不一致。它可能是SO的渲染器正在拾取的空間與標籤問題。嘗試用'python -tt'運行你的腳本,看看它是否失敗。即使沒有,你也應該保持一致。 – mgilson