我的主要问题是通过尝试file://
添加到相对路径来获取错误的 URL。可以这样修复:
webbrowser.open('file://' + os.path.realpath(filename))
Usingwebbrowser.open
将尝试多种方法,直到一个“成功”,这是一个松散的定义。
失败并返回的WindowsDefault
类调用。我可以通过在 windows 运行命令中输入 URL 并看到错误消息而不是浏览器来验证这一点。os.startfile()
False
两者GenericBrowser
和BackgroundBrowser
都将subprocess.Popen()
使用一个成功的 exe 调用,即使 URL 不正确,并返回True
. IE 没有给出问题的指示,所有其他浏览器都有一个很好的消息说他们找不到文件。
GenericBrowser
由环境变量设置BROWSER
并且是第一个。
WindowsDefault
是第二个。
BackgroundBrowser
是最后一个,如果没有其他方法,则包括后备 IE。
这是我的原始设置:
>>> import webbrowser
>>> webbrowser._tryorder
['windows-default',
'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
('c:\\program files\\internet explorer\\iexplore.exe', [None, <webbrowser.BackgroundBrowser object at 0x00000000022E3898>])]
>>>
这是我修改环境变量后的设置:
C:>path=C:\Program Files (x86)\Mozilla Firefox;%path%
C:>set BROWSER=C:\Users\Scott\AppData\Local\Google\Chrome\Application\chrome.exe
C:>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> webbrowser._tryorder
['C:\\Users\\Scott\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
'windows-default',
'firefox',
'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
('c:\\program files\\internet explorer\\iexplore.exe',[None, <webbrowser.BackgroundBrowser object at 0x000000000235E828>]),
('firefox', [None, <webbrowser.BackgroundBrowser object at 0x000000000235E780>]),
('c:\\users\\scott\\appdata\\local\\google\\chrome\\application\\chrome.exe', [None, <webbrowser.GenericBrowser object at 0x000000000235E8D0>])]
>>>
给出了尝试过的webbrowser._tryorder
浏览器列表。注册 chrome 或添加 BROWSER env var 或修改我的路径都会为我提供正确的浏览器和更好的错误消息。
感谢您的帮助,如果没有您的想法,我无法解决这个问题。