5

My script runs a command every X seconds.

If a command is like "start www" -> opens a website in a default browser I want to be able to close the browser before next time the command gets executed.

This short part of a script below:

if "start www" in command:
    time.sleep(interval - 1)
    os.system("Taskkill /IM chrome.exe /F")

I want to be able to support firefox, ie, chrome and opera, and only close the browser that opened by URL.

For that I need to know which process to kill.

How can I use python to identify my os`s default browser in windows?

  • How are you _opening_ the browser by URL? `webbrowser.open`? `os.startfile`? Running `'start "{}"'.format(url)` via `os.system`? Using a third-party module? – abarnert Sep 26 '13 at 19:47
  • try this: http://stackoverflow.com/questions/5916270/pythons-webbrowser-launches-ie-instead-of-default-on-windows-7 – Vivek Sep 26 '13 at 19:47
  • 1
    @Vivek: I don't think that answers the OP's question. He apparently already knows how to open a web page (although he hasn't told us how he's doing it). He just wants to know how to kill the process used to open that web page. – abarnert Sep 26 '13 at 19:49
  • 1
    Meanwhile… are you sure you want to do it? If I've already got my default browser open with 48 tabs in 6 windows, and your script pops open a new window, then kills the browser taking down my 6 existing windows, I'm not going to be too happy… – abarnert Sep 26 '13 at 19:50
  • I am using os.system(command) - if command = "start www.google.com" it starts default browser – Michał Węgrzyn Sep 26 '13 at 19:51
  • First, as a side issue, using `os.system("start www.google.com")` is not a great idea. `os.startfile("www.google.com")` will do the same thing, but without spawning an extra shell for no reason, and without requiring you to worry about quoting the argument if it has spaces or other special characters in it, and so on. But that doesn't answer your real question; it's a completely separate issue. – abarnert Sep 26 '13 at 19:53

2 Answers2

8

The solution is going to differ from OS to OS. On Windows, the default browser (i.e. the default handler for the http protocol) can be read from the registry at:

HKEY_CURRENT_USER\Software\Classes\http\shell\open\command\(Default)

Python has a module for dealing with the Windows registry, so you should be able to do:

from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore

with OpenKey(HKEY_CURRENT_USER,
             r"Software\Classes\http\shell\open\command") as key:
    cmd = QueryValue(key, None)

You'll get back a command line string that has a %1 token in it where the URL to be opened should be inserted.

You should probably be using the subprocess module to handle launching the browser; you can retain the browser's process object and kill that exact instance of the browser instead of blindly killing all processes having the same executable name. If I already have my default browser open, I'm going to be pretty cheesed if you just kill it without warning. Of course, some browsers don't support multiple instances; the second instance just passes the URL to the existing process, so you may not be able to kill it anyway.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • This is really only the right answer if he's using `os.startfile` or `start` via `os.system`… but since that apparently _is_ what he's doing, +1. – abarnert Sep 26 '13 at 19:54
  • OK, how to use subprocess to launch a command "start www.google". I am having a difficult time with this one. – Michał Węgrzyn Sep 26 '13 at 20:53
  • Don't use `start`. `start` goes away immediately after handing off control to the browser. Launch the browser directly. – kindall Sep 26 '13 at 20:59
  • No such registry key on Windows 10, this is because the key uses an underlying default, struggling to locate that right now. Alternates? –  Jul 30 '20 at 09:12
  • This path does not exist for me on Windows 10. Check paths at https://superuser.com/a/1111131/1462649 – Zois Tasoulas Oct 10 '22 at 22:14
3

I would suggest this. Honestly Python should include this in the webbrowser module that unfortunately only does an open bla.html and that breaks anchors on the file:// protocol.

Calling the browser directly however works:

    # Setting fallback value
browser_path = shutil.which('open')

osPlatform = platform.system()

if osPlatform == 'Windows':
    # Find the default browser by interrogating the registry
    try:
        from winreg import HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, OpenKey, QueryValueEx

        with OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice') as regkey:
            # Get the user choice
            browser_choice = QueryValueEx(regkey, 'ProgId')[0]

        with OpenKey(HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(browser_choice)) as regkey:
            # Get the application the user's choice refers to in the application registrations
            browser_path_tuple = QueryValueEx(regkey, None)

            # This is a bit sketchy and assumes that the path will always be in double quotes
            browser_path = browser_path_tuple[0].split('"')[1]

    except Exception:
        log.error('Failed to look up default browser in system registry. Using fallback value.')