DIsplay an exception in the web browser.

Gribouillis 0 Tallied Votes 244 Views Share

This snippet defines a function exc_browse() which displays the current python exception in the web browser. This can be useful to non web programmers who want a nicely displayed exception traceback (web frameworks usually include this feature). The idea of this function is to store the html code generated by the method cgitb.html in a temporary file and open this temporary file with the webbrowser module.

# tested with python 2.6 and 3.1

def exc_browse(browser = None):
    """exc_browser() --> True on success, False on failure
    
    Display the last exception raised in a web browser. This function is
    meant to be used in except statements (see example below).
    The optional 'browser' argument is a string which can have a value accepted
    by webbrowser.get().
    
    A temporary html file is created (named after the current process pid).
    
    example:
        
        try:
            c = "hello world"[100]
        except IndexError:
            exc_browse() # displays the exception in the web browser
    """
    
    import os, sys, cgitb
    html = cgitb.html(sys.exc_info())
    tdir = None
    if sys.platform == 'linux2' and os.path.isdir('/dev/shm'):
        # under linux, try to create the temporary file in shared memory
        tdir = '/dev/shm'
        if not os.path.isdir(tdir):
            tdir = None
    if tdir is None:
        from tempfile import gettempdir
        tdir = gettempdir()
    tdir = os.path.join(tdir, "exc_browse")
    if not os.path.isdir(tdir):
        try:
            os.mkdir(tdir)
        except OSError:
            return False
    name = "exc%d.html" % os.getpid()
    fname = os.path.join(tdir, name)
    try:
        if os.path.isfile(fname):
            try:
                os.unlink(fname)
            except OSError:
                return False
        f = open(fname, "w")
        f.write(html)
        f.close()
    except (OSError, IOError):
        return False
    import webbrowser
    if browser is not None:
        w = webbrowser.get(browser)
    else:
        w = webbrowser
    return w.open(fname)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.