Interview Questions

How to Debugging in python?

Python Questions and Answers


(Continued from previous question...)

How to Debugging in python?

Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server.

For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML:

#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb; cgitb.enable()
print 1/0

The handler() method can be used to handle only the catched exceptions:

#!/usr/bin/env python
print "Content-Type: text/html"
print
import cgitb
try:
f = open('non-existent-file.txt', 'r')
except:
cgitb.handler()

There is also the option for a crude approach making the header "text/plain" and setting the standard error to standard out:

#!/usr/bin/env python
print "Content-Type: text/plain"
print
import sys
sys.stderr = sys.stdout
f = open('non-existent-file.txt', 'r')

Will output this:

Traceback (most recent call last):
File "/var/www/html/teste/cgi-bin/text_error.py", line 6, in ?
f = open('non-existent-file.txt', 'r')
IOError: [Errno 2] No such file or directory: 'non-existent-file.txt'

Warning: These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable it.

(Continued on next question...)

Other Interview Questions