0

I'm using python3. I want to print the time a script fails, as well as the corresponding exception in one line. Referring to this link & this one, I tried something like this, but the function didn't execute. Am I doing something wrong here? Would appreciate suggestions.


import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    try:
        print("")
    except:
        print('Script ended at date/time: %s with error %s.' % (date_and_time, error))

import atexit
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

print "Deliberate error" # Simple example of an error that should be caught & printed along with time when script fails.

# main body of script continues here
#
#

1 Answer 1

2

Your script has multiple problems. (datetime not imported, useless try/except in f_log, ...) The main issue is that a SyntaxError can't be handled. Try this version instead:

import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    print('Script ended at date/time: %s with error %s.' % (date_and_time, error))


atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

1/0 # Simple example of an error that should be caught & printed along with time when script fails.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was unaware that a SyntaxError couldn't be handled this way; the error example you used seems to be caught with no problem. I guess I will have to look deeper into which kinds of Exceptions are, well, exceptions. On another note, I hadn't explicitly included the "import" lines in the code snippet here because it isn't related to the problem I had; but after seeing your comment, I've edited my post for clarity so others don't similarly assume that that could be a potential source of error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.