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.
JavaScript
x
19
19
1
import atexit
2
import datetime
3
4
#define function to log when script ends due to error/failure
5
def f_log(date_and_time, error):
6
try:
7
print("")
8
except:
9
print('Script ended at date/time: %s with error %s.' % (date_and_time, error))
10
11
import atexit
12
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)
13
14
print "Deliberate error" # Simple example of an error that should be caught & printed along with time when script fails.
15
16
# main body of script continues here
17
#
18
#
19
Advertisement
Answer
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:
JavaScript
1
12
12
1
import atexit
2
import datetime
3
4
#define function to log when script ends due to error/failure
5
def f_log(date_and_time, error):
6
print('Script ended at date/time: %s with error %s.' % (date_and_time, error))
7
8
9
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)
10
11
1/0 # Simple example of an error that should be caught & printed along with time when script fails.
12