Skip to main content
 首页 » 编程设计

python之尝试缩进错误,除了,python中的else block

2025年05月04日17java哥

我问了一个问题here ,我一直在整理错误异常。 我已经整理好了从另一个文件中读取文件列表的问题,但是如果引用的文件之一不存在,我就会苦苦挣扎。 我希望能够识别错误,通过电子邮件发送出去,然后创建文件供以后使用。 但是,对于我放入的“try, except, else” block ,我遇到了缩进错误。 看起来它应该可以工作,但我就是无法让它运行! 啊!帮忙!!!

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

//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: 
        .... 

那样的话,try 和except 之间永远不会有很多行,并且可以避免嵌套try/except block 。