Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 webbrowser
webbrowser.get("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s").open("http://google.com")

The path is correct and print does give me a Handler:

"<webbrowser.GenericBrowser object at 0x0000000002D26518\>"

However, the open() - preferably open_new_tab()) - function does not work. It returns False.

If I run the command

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "https://google.com"

in windows run dialog, it does do work, though.


If I set Chrome as standard browser and run

webbrowser.get().open("http://google.com")

it does work, but it's not what I want.

Has anyone an idea what's going wrong?

like image 212
Vankog Avatar asked Oct 27 '25 08:10

Vankog


2 Answers

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.

like image 185
dano Avatar answered Oct 29 '25 21:10

dano


You don't need to switch to Unix-style paths -- simply quote the executable.

import webbrowser
webbrowser.get('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %s').open('http://google.com')
like image 22
P-Gn Avatar answered Oct 29 '25 21:10

P-Gn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!