Juicy lil' bytes

How to Open a URL in the Default Browser Across OS Platforms

Programmatically launching a URL in the default browser across OS platforms is not as widely supported as you might think. The Python webbrowser module provides fairly broad support for this. Here’s a shell one-liner and a Python script that allow you to do it.

Shell Command

You can run this as a one liner in your shell with the following syntax:

1
python -m webbrowser <URL>

To open the URL in a new tab, use the -t switch, and to open it in a new browser window, use the -n switch like this:

Open Sweetmeat in a New Tab

1
python -m webbrowser -t "http://sweetme.at"

Open Sweetmeat in a New Window

1
python -m webbrowser -n "http://sweetme.at"

Python Scripts

Import the webbrowser module and use the following module function:

1
2
3
4
import webbrowser

url = "http://sweetme.at"
webbrowser.open_new_tab(url)

This opens the URL in a new tab with a fallback to a new browser window if this fails. To make a new window the default, use the following:

1
2
3
4
import webbrowser

url = "http://sweetme.at"
webbrowser.open_new(url)

Python Docs

Here are the webbrowser module docs for Python versions 2.7 and 3.3. There are a few more examples and details on possible exceptions that are raised with these scripts.