Python is the interpreter language, you do not need to compile your code, and also you have no ways to check for your syntax error until you run your python script. Either syntax error or runtime error will be throw to standard output through python exception handler by default.
Python throw the exception with traceback info indicate that which part of your scripts has gone wrong, it looks like this:
Traceback (most recent call last): File "except.py", line 9, in
main() File "except.py", line 5, in main print l IndexError: list index out of range
The traceback indicate me that there is an IndexError happen in my main function. This piece of good info are very helpful for me to do the debugging. But we might use python for some automated jobs where I runs my python scripts with crontab. So its hard for me to discover my bugs with the traceback throw to the screen.
So this question comes to my head.
” Can I log the traceback into a text file and let the python script ends peacefully?”
First of all, I thought I can get it from Exception class, but the fact is I can only get it from traceback class, check out the sample here:
#!/usr/bin/env python import sys, traceback def main(): l=[1,2,3,4] print l if __name__=="__main__": try: main() except: print "Trigger Exception, traceback info forward to log file." traceback.print_exc(file=open("errlog.txt","a")) sys.exit(1)
By using traceback.print_exc() I can now append the exception traceback to my log file.