views:

1083

answers:

6

Hi,

I'm trying to launch a website url in a new tab using python in that way, but it didn't worked in these both ways:

Method 1:

os.system('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/');

and Method 2:

os.startfile('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/');

If I don't add the parameters (-new-tab http://www.google.com/) it works, opening the default page.

+15  A: 

You need to use the webbrowser module

import webbrowser
webbrowser.open('http://www.google.com')

[edit]

If you want to open a url in a non-default browser try:

webbrowser.get('firefox').open_new_tab('http://www.google.com')
Nadia Alramli
Yes, but what if my default browser is not Firefox?
Leandro Ardissone
If the user's default browser is not Firefox, should you force them to use it?
John Fouhy
Nice tip. Thanks. But still don't open the page in a new tab instead of new window. Thanks.
Leandro Ardissone
@John: I'm trying to provide a .xpi extension from an URL, so I need the user to open it with Firefox (no Flock or any other associated app).
Leandro Ardissone
@Leandro I changed the call to open_new_tab it should open a new tab now
Nadia Alramli
Interesting... I've never played with the webbrowser module before. I'll have to stash that one off in the back of my brain for future use. Thanks Nadia.
D.Shawley
@Nadia, awesome! Really easy solution!
Leandro Ardissone
Ah, I've noticed that it doesn't work on Windows, get this error: "could not locate runnable browser"
Leandro Ardissone
Nadia Alramli
Cool, I've added the firefox to the BROWSER env var, but no luck, I'll check with the PATH. Thx.
Leandro Ardissone
FWIW, I only needed to add the mozilla\firefox installation directory to my PATH -- no other env vars were needed to make `webbrowser` work with firefox and Python 2.7.
martineau
A: 

Use os.startfile() passing only the url. This will cause the URL to be opened in a new tab/window in the user's default browser, which is much nicer to your user.

James Emerton
Same issue, I need to open it in Firefox instead of the default browser.
Leandro Ardissone
+2  A: 

If you want to start a program with parameters the subprocess module is a better fit:

import subprocess
subprocess.call([r'C:\Program Files\Mozilla Firefox\Firefox.exe',
    '-new-tab', 'http://www.google.com/'])
sth
Awesome, thank you!
Leandro Ardissone
what if firefox was not installed? what if it was installed in a different directory? this is not the right way to do. Even if it works in some cases
Nadia Alramli
A: 

You might want to try:

import os
os.spawnl(os.P_NOWAIT, r'C:\Program Files\Mozilla Firefox\Firefox.exe',
          r'FireFox', '-new-tab', 'http://www.google.com/')
D.Shawley
A: 

And how do I open a new tab in the background?

sel
A: 
leena