Coder Perfect

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


What can I use to call the OS to open a URL in whatever browser the user has as default? Not worried about cross-OS compatibility; if it works in linux thats enough for 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):

On Linux, Ubuntu 10.10, I was able to successfully test this.

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

On popular platforms, this will result in a better user experience. On other platforms, you might be able to use a webbrowser. However, if you’re using an obscure/unusual/embedded OS that doesn’t support any of the above, chances are your webbrowser will as well.

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