簡體   English   中英

嘗試時出現縮進錯誤,但在Python中else阻塞

[英]Indentation error on try, except, else block in python

除了我在這里提出的一個問題之外,我還堅持要整理一個錯誤異常。 我已經整理好了從另一個文件中讀取文件列表的方法,但是我在為所引用的文件之一不存在而苦苦掙扎。 我希望能夠識別錯誤,通過電子郵件發送出去,然后創建文件以供以后使用。 但是,我正在插入的“ try,except,else”塊出現縮進錯誤。看起來應該可以,但無法運行! 加! 救命!!!

日志文本文件包含以下內容:

//server-1/data/instances/devapp/log/audit.log

//server-1/data/instances/devapp/log/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 = 'errors@company.com'
receivers = 'bob@company.com'
message_1 = """From: errors <errors@company.com>
To: Bob <bob@company.com>
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

據我所知,它應該可以,但是...

另外要注意的是,我學習的時間並不長,因此我的很多代碼都從各種教程中進行了修改,或者從這里或網上的其他地方借來的。 我可能在這里犯了一個非常基本的錯誤,所以如果我願意,請多包涵!

非常感謝您的幫助!

您在此行下沒有代碼塊:

with open(line.strip()) as logs:

try:def ...:with ...:for ...:這樣的每一行都需要在其下包含一個縮進的代碼塊。

為了回答您的評論,您可能希望將代碼分成較小的函數,以使事情更清楚。 所以你有這樣的事情:

def sendEmail(...):
    try:
        smtpObj = smtplib.SMTP('localhost')
        ...
    except SMTPException:
        ...

def log_opener(...):
    try:
        with open(line.strip()) as logs:
            sendEmail(...)
    except (OSError,IOError), e:
        ....

這樣,您就不會在tryexcept之間有太多的界限,並且避免嵌套try/except塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM