Coder Perfect

To open a URL, do I need to make a call to the operating system?


What command can I provide to get the OS to open a URL in the user’s default browser? I’m not concerned with cross-OS compatibility; if it works under Linux, that’s all that matters to me!

Asked by Bolster

Solution #1

To launch the user’s default browser with a specific url, follow these steps:

import webbrowser[, new=0[, autoraise=True]])

This functionality’s documentation may be found here. It’s part of Python’s standard library (stdlibs):

I have tested this successfully on Linux, Ubuntu 10.10.

Answered by kobrien

Solution #2

Personally, I wouldn’t bother with the webbrowser module.

It’s a jumble of sniffing for specific browsers that won’t identify the user’s default browser if they have others installed, and won’t find a browser if it doesn’t recognize the name (eg Chrome).

On Windows, the os.startfile function, which also works with a URL, is preferable. You can use the open system command on OS X. GNOME, KDE, and XFCE all support the standard command xdg-open on Linux.

if sys.platform=='win32':
elif sys.platform=='darwin':
    subprocess.Popen(['open', url])
        subprocess.Popen(['xdg-open', url])
    except OSError:
        print 'Please open a browser on: '+url

This will give a better user experience on mainstream platforms. On other platforms, you might be able to use a webbrowser. Though most likely if you’re on an obscure/unusual/embedded OS where none of the above work, chances are webbrowser will fail too.

Answered by bobince

Solution #3

The webbrowser module can be used.

Answered by Ivo Wetzel

Solution #4

Then how about combining @kobrien and @bobince’s codes:

import subprocess
import webbrowser
import sys

url = ''
if sys.platform == 'darwin':    # in case of OS X
    subprocess.Popen(['open', url])

Answered by Kenial

Solution #5

Take a look at the module webbrowser.

Answered by Aaron Digulla

Post is based on