Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a name of default browser using python

Tags:

python

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?

like image 681
Michał Węgrzyn Avatar asked Jan 13 '23 06:01

Michał Węgrzyn


1 Answers

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.

like image 174
kindall Avatar answered Jan 22 '23 20:01

kindall