Call to operating system to open url?

PythonLinuxUrlOperating System

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

Here is how to open the user's default browser with a given url:

import webbrowser

url = "https://www.google.com/"

webbrowser.open(url, new=0, autoraise=True)

Here is the documentation about this functionality. It's part of Python's stdlibs:

http://docs.python.org/library/webbrowser.html

I have tested this successfully on Linux, Ubuntu 10.10.

Solution 2 - Python

Personally I really wouldn't use the webbrowser module.

It's a complicated mess of sniffing for particular browsers, which will won't find the user's default browser if they have more than one installed, and won't find a browser if it doesn't know the name of it (eg Chrome).

Better on Windows is simply to use the os.startfile function, which also works on a URL. On OS X, you can use the open system command. On Linux there's xdg-open, a freedesktop.org standard command supported by GNOME, KDE and XFCE.

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

This will give a better user experience on mainstream platforms. You could fall back to webbrowser on other platforms, perhaps. Though most likely if you're on an obscure/unusual/embedded OS where none of the above work, chances are webbrowser will fail too.

Solution 3 - Python

You can use the webbrowser module.

webbrowser.open(url)

Solution 4 - Python

Then how about mixing codes of @kobrien and @bobince up:

import subprocess
import webbrowser
import sys

url = 'http://test.com'
if sys.platform == 'darwin':    # in case of OS X
    subprocess.Popen(['open', url])
else:
    webbrowser.open_new_tab(url)

Solution 5 - Python

Have a look at the webbrowser module.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBolsterView Question on Stackoverflow
Solution 1 - PythonkobrienView Answer on Stackoverflow
Solution 2 - PythonbobinceView Answer on Stackoverflow
Solution 3 - PythonIvo WetzelView Answer on Stackoverflow
Solution 4 - PythonKenialView Answer on Stackoverflow
Solution 5 - PythonAaron DigullaView Answer on Stackoverflow