2 min read

Python Cgitb Module

The cgitb module provides a special exception handler for Python scripts. (The name stands for "CGI Traceback".) It is primarily designed to help debug CGI scripts by formatting tracebacks as detailed HTML reports, but it can also be used in other contexts to produce rich text-based tracebacks.

Importing the Module

import cgitb

Basic Usage

To enable the cgitb exception handler, simply call the enable() function at the top of your script.

import cgitb
cgitb.enable()

When an uncaught exception occurs, cgitb will take over and display a detailed report. By default, this report is formatted as HTML and printed to standard output (which is useful for CGI scripts running in a web server).

Configuration Options

The enable() function accepts several optional arguments to customize its behavior.

display

If display is set to 1 (the default), the traceback is sent to the browser (stdout). If set to 0, the traceback is suppressed.

logdir

If logdir is specified, the traceback reports are written to files in that directory. This is useful if you don't want to show errors to the user but still want to record them.

import cgitb
import os

# Create a directory for logs if it doesn't exist
if not os.path.exists('logs'):
    os.makedirs('logs')

# Enable cgitb, don't display to user, log to 'logs' directory
cgitb.enable(display=0, logdir='logs')

format

The format argument controls the output format.

  • "html" (default): Produces an HTML report.
  • "text": Produces a plain text report.
import cgitb

# Enable text-based reporting
cgitb.enable(format='text')

def func(a, b):
    return a / b

func(1, 0) # This will trigger the cgitb handler

programming/python/python