Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set BROWSER environmental variable for python webbrowser

I'm trying to register the Firefox browser to run on Windows. According to the documentation for Webbrowser, "If the environment variable BROWSER exists, it is interpreted to override the platform default list of browsers, as a os.pathsep-separated list of browsers to try in order". I have the following:

import os
import webbrowser
from subprocess import call

os.environ["BROWSER"] = "C:\\FirefoxPortable\\FirefoxPortable.exe"
webbrowser.open('http://google.com')

This still opens iexplorer ( the default browser ).

Also:

>>> webbrowser._browsers
{'windows-default': [<class 'webbrowser.WindowsDefault'>, None], 'c:\\program files\\internet explorer\\iexplore.exe': [None, <webbrowser.BackgroundBrowser object at 0x04A18F90>]}
>>> webbrowser._tryorder
['windows-default', 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']

How Can I use Firefox here?

Source:

# OK, now that we know what the default preference orders for each
# platform are, allow user to override them with the BROWSER variable.
if "BROWSER" in os.environ:
    _userchoices = os.environ["BROWSER"].split(os.pathsep)
    _userchoices.reverse()

    # Treat choices in same way as if passed into get() but do register
    # and prepend to _tryorder
    for cmdline in _userchoices:
        if cmdline != '':
            cmd = _synthesize(cmdline, -1)
            if cmd[1] is None:
                register(cmdline, None, GenericBrowser(cmdline), -1)
    cmdline = None # to make del work if _userchoices was empty
    del cmdline
    del _userchoices

# what to do if _tryorder is now empty?
like image 601
user1592380 Avatar asked Mar 18 '23 11:03

user1592380


2 Answers

Tried your example and got the same result: Was opening in IE, not in Firefox. Reason is, that at import time of webbrowser, the BROWSER environment variable is not yet set. By simply reordering:

import os
# put it **before** importing webbroser
os.environ["BROWSER"] = "C:\\FirefoxPortable\\FirefoxPortable.exe"
import webbrowser
# from subprocess import call

webbrowser.open('http://google.com')

it works now. I figured that by trying to set the environment variable on the command line. Note: It did not work having the path in quotes

set BROWSER=C:\FirefoxPortable\FirefoxPortable.exe

did work,

set BROWSER="C:\FirefoxPortable\FirefoxPortable.exe"

did not. Sorry for the late answer, but the diagnostics with

>>> webbrowser._browsers
>>> webbrowser._tryorder

had been very helpful, thanks.

like image 111
nepix32 Avatar answered Apr 08 '23 02:04

nepix32


Try the following code:

webbrowser.register('firefox', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'))
a=webbrowser.get('firefox')
a.open("www.google.com")­­­­­
like image 41
Serkan Deveci Avatar answered Apr 08 '23 01:04

Serkan Deveci