1

Further to a question I asked here, I'm stuck sorting out an error exception. I have sorted out reading a list of files from another file, but I'm struggling with if one of the files referenced doesn't exist. I want to be able to identify the error, email out and then create the file for later use. However, I'm getting an indentation error for the "try, except, else" block I'm putting in. It looks like it should work but I just can't get it to run! Gah! Help!!!

The log text file contains the following:

//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 # This file doesn't exist on the server

My code is as follows. I thought it best to post it in entirety rather than a snippet, in case it's something earlier in the program that's knackering it!

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)

The error I'm getting is as follows:

$ python log_5.py
  File "log_5.py", line 38
    except (OSError,IOError), e:
    ^
IndentationError: expected an indented block

As far as I can tell, it should work but...

As an additional note, I've not been learning long, so a lot of my code is modified from various tutorials or borrowed from here, or elsewhere on the web. I'm probably making a very basic mistake here, so bear with me if I am!

Many thanks for your help!

1
  • 1
    Clearly your indentation isn't consistent between the first try/except and the indentation in the function. It might be a spaces vs. tabs issue which SO's renderer is picking up. Try running your script with python -tt and see if it fails. Even if it doesn't, you should make that consistent. Commented May 16, 2013 at 19:51

1 Answer 1

6

You have no code block under this line:

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

Every line like try:, def ...:, with ...:, for ...: needs to have an indented block of code under it.

In answer to your comment, you might want to break your code into smaller functions, to make things clearer. So you have something like:

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

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

That way, you never have lots of lines between the try and the except, and you avoid having nested try/except blocks.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought that, but couldn't figure out how to catch the error that is thrown at that point without going straight to the except...
@BobHoward You can add pass in the block, which says "do nothing".
@ RichieHindle - I thought about doing that, but couldn't figure out how to get that to call with the exception, as I only want to send the email if the file isn't there. As I said, I'm a newb at this. I'[ll have a look at my code and see if I can get it to work that way as it looks like that would be much better! Many thanks for your replies. They have helped me understand where I'm going with this a lot more! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.