gpt4 book ai didi

python - 如何为python webbrowser设置BROWSER环境变量

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:37 24 4
gpt4 key购买 nike

我正在尝试注册 Firefox 浏览器以在 Windows 上运行。根据 Webbrowser 的文档,“如果环境变量 BROWSER 存在,它被解释为覆盖浏览器的平台默认列表,作为 os.pathsep 分隔的浏览器列表以按顺序尝试”。我有以下内容:

import os
import webbrowser
from subprocess import call

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

这仍然会打开 iexplorer(默认浏览器)。

还有:

>>> 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']

如何在这里使用 Firefox?

来源:

# 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?

最佳答案

尝试了您的示例并得到了相同的结果:在 IE 中打开,而不是在 Firefox 中打开。原因是,在导入 webbrowser 时,尚未设置 BROWSER 环境变量。通过简单地重新排序:

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')

现在可以了。我想通过尝试在命令行上设置环境变量。注意:引号中的路径不起作用

set BROWSER=C:\FirefoxPortable\FirefoxPortable.exe

成功了,

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

没有。很抱歉回答晚了,但是

的诊断
>>> webbrowser._browsers
>>> webbrowser._tryorder

非常有帮助,谢谢。

关于python - 如何为python webbrowser设置BROWSER环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25875093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com