我的主要问题是尝试添加错误的 URLfile://
到相对路径。可以这样修复:
webbrowser.open('file://' + os.path.realpath(filename))
Using webbrowser.open
将尝试多种方法,直到一种“成功”,这是一个宽松的定义。
The WindowsDefault
班级电话os.startfile()
失败并返回False
。我可以通过在 Windows 运行命令中输入 URL 并看到错误消息而不是浏览器来验证这一点。
Both GenericBrowser
and BackgroundBrowser
将会通知subprocess.Popen()
即使 URL 错误,exe 也会成功,并返回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>])]
>>>
The webbrowser._tryorder
给出尝试过的浏览器列表。注册 chrome 或添加浏览器环境变量或修改我的路径都会让我获得正确的浏览器和更好的错误消息。
感谢您的帮助,没有您的想法我无法解决这个问题。