Live Chat!

python: convey the exception traceback into log file

* * * * * 2 votos

February 27th, 2008 mysurface Posted in Developer, python | Hits: 14138 |

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[4]
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[4]

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.

2 Responses to “python: convey the exception traceback into log file”

  1. i think it,s a great post.

  2. Abdul Rahman Says:

    I use internet through Mobile. I am using bluetooth device to connect my mobile and pc. I have been using Microsoft and Fedora 7 linux. Linux installed in another partition. I want to surf internet in Linux. But, I can’t install Bluetooth software in Linux. Can anyone help me to resolve this problem?

Leave a Reply