Search code examples
pythonpython-webbrowser

Python webbrowser - Check if browser is available (nothing happens when opening webpage over an SSH connection)


Is there a way to detect whether there is a browser available on the system on which the script is run? Nothing happens when running the following code on a server:

try:
    webbrowser.open("file://" + os.path.realpath(path))
except webbrowser.Error:
    print "Something went wrong when opening webbrowser"

It's weird that there's no caught exception, and no open browser. I'm running the script from command line over an SSH-connection, and I'm not very proficient in server-related stuff, so there may be another way of detecting this that I am missing.

Thanks!


Solution

  • Checkout the documentation:

    webbrowser.get([name])

    Return a controller object for the browser type name. If name is empty, return a controller for a default browser appropriate to the caller’s environment.

    This works for me:

    try:
        # we are not really interested in the return value
        webbrowser.get()
        webbrowser.open("file://" + os.path.realpath(path))
    except Exception as e:
        print "Webbrowser error: " % e
    

    Output:

    Webbrowser error: could not locate runnable browser