4

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?

4

2 回答 2

8

解决方案将因操作系统而异。http在 Windows 上,可以从注册表中读取默认浏览器(即协议的默认处理程序):

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

Python 有一个用于处理 Windows 注册表的模块,因此您应该能够:

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)

您将返回一个命令行字符串,其中包含一个%1标记,要在其中插入要打开的 URL。

您可能应该使用该subprocess模块来处理启动浏览器;您可以保留浏览器的进程对象并杀死该浏览器的确切实例,而不是盲目地杀死所有具有相同可执行文件名称的进程。如果我已经打开了我的默认浏览器,如果你在没有警告的情况下直接杀死它,我会很生气。当然,有些浏览器不支持多实例;第二个实例只是将 URL 传递给现有进程,因此您可能无论如何都无法杀死它。

于 2013-09-26T19:51:01.893 回答
1

我会建议这个。老实说,Python 应该将它包含在 webbrowser 模块中,不幸的是,它只打开了 bla.html 并且破坏了 file:// 协议上的锚点。

但是直接调用浏览器可以:

    # 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.')
于 2021-07-07T20:33:17.570 回答