Linux
自動檢測已經打開的瀏覽器而不是打開預設瀏覽器
我的系統上有多個瀏覽器(Firefox、Google Chrome 和 Chromium)。
我通常根據自己的需要一次使用其中一個,但是當其他應用程序想要打開瀏覽器時,他們總是打開他們的/系統預設瀏覽器。
是否有能夠檢測瀏覽器是否已在執行並將其用作目前預設瀏覽器的應用程序或腳本?
編輯
我不希望瀏覽器檢測到自己的實例!我想要一個瀏覽器請求程序/腳本來檢測任何已經打開的瀏覽器。
- 例如,假設我有 Firefox、Google Chrome 和 Chromium,並且我點擊 PDF 文件中的連結,並且 Chromium 已經打開。我希望在 Chromium 中打開連結。
- 在另一個時間,Firefox 是打開的。然後我希望在 Firefox 中打開連結。
實際上,我希望已經打開的瀏覽器具有比系統預設瀏覽器更高的優先級。
以下 Python 程序使用psutil模組獲取屬於您的程序列表,檢查是否有已知瀏覽器正在執行,如果是,則再次啟動該瀏覽器。如果找不到瀏覽器,則啟動預設瀏覽器。我添加了一些註釋來澄清腳本中發生了什麼。
除了腳本本身,您還需要使用chmod使這個執行檔,並確保腳本被執行而不是啟動特定的瀏覽器。
#!/usr/bin/env python import psutil import os import subprocess import sys import pwd def getlogin(): return pwd.getpwuid(os.geteuid()).pw_name def start_browser(exe_path): # Popen should start the process in the background # We'll also append any command line arguments subprocess.Popen(exe_path + sys.argv[1:]) def main(): # Get our own username, to see which processes are relevant me = getlogin() # Process names from the process list are linked to the executable # name needed to start the browser (it's possible that it's not the # same). The commands are specified as a list so that we can append # command line arguments in the Popen call. known_browsers = { "chrome": [ "google-chrome-stable" ], "chromium": [ "chromium" ], "firefox": [ "firefox" ] } # If no current browser process is detected, the following command # will be executed (again specified as a list) default_exe = [ "firefox" ] started = False # Iterate over all processes for p in psutil.process_iter(): try: info = p.as_dict(attrs = [ "username", "exe" ]) except psutil.NoSuchProcess: pass else: # If we're the one running the process we can # get the name of the executable and compare it to # the 'known_browsers' dictionary if info["username"] == me and info["exe"]: print(info) exe_name = os.path.basename(info["exe"]) if exe_name in known_browsers: start_browser(known_browsers[exe_name]) started = True break # If we didn't start any browser yet, start a default one if not started: start_browser(default_exe) if __name__ == "__main__": main()