webbrowser | Python Batteries

Today’s reverse spelunking through the Python standard library reveals the webbrowser module. As a library, it allows a Python application to interact with the default web browser on the host OS, opening a url in a new browser window or tab. This functionality is exposed at the shell, as well:

$ python -m webbrowser
Usage: /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/webbrowser.py [-n | -t] url
    -n: open new window
    -t: open new tab

You can use the webbrowser module like this to open web pages from any shell or shell script.

$ python -m webbrowser -t http://www.civilfritz.net/

The module does what it can to do the right thing given your environment, and will open a browser on X11, OS X, Windows, and will even open a text–mode browser if no graphical browser is available.

I noticed (on OS X, anyway) that if you don’t specify a protocol (e.g., http) you get an exception.

$ python -m webbrowser -n www.civilfritz.net
0:39: execution error: An error of type -2110 has occurred. (-2110)

The browser still opened successfully, though.

You can find more information on the webbrowser module at the Python website.