Python: generic webbrowser.get().open() for chrome.exe does not work

前端 未结 6 1462
天命终不由人
天命终不由人 2020-12-11 09:48

I am on Python 2.7 (Win 8.1 x64) and I want to open a URL in Chrome. As Chrome is only natively supported in 3.3+, I was trying a generic call:

import webbro         


        
6条回答
  •  春和景丽
    2020-12-11 10:30

    You have to use unix-style paths in the webbrowser.get call:

    webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")
    

    This is because webbrowser internally does a shlex.split on the path, which will just erase Windows-style path separators:

    >>> cmd = "C:\\Users\\oreild1\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe %s"
    >>> shlex.split(cmd)
    ['C:Usersoreild1AppDataLocalGoogleChromeApplicationchrome.exe', '%s']
    >>> cmd = "C:/Users/dan/AppData/Local/Google/Chrome/Application/chrome.exe %
    s"
    >>> shlex.split(cmd)
    ['C:/Users/dan/AppData/Local/Google/Chrome/Application/chrome.exe', '%s']
    

    shlex will actually do the right thing here if given the posix=False keyword argument, but webbrowser won't supply that, even on Windows. This is arguably a bug in webbrowser.

提交回复
热议问题