기본 브라우저를 여는 대신 열려 있는 브라우저를 자동으로 감지합니다.

기본 브라우저를 여는 대신 열려 있는 브라우저를 자동으로 감지합니다.

내 시스템에는 여러 브라우저(Firefox, Google Chrome, Chromium)가 있습니다.
나는 보통 필요에 따라 한 번에 이들 중 하나를 사용하지만 다른 응용 프로그램이 브라우저를 열려고 할 때 항상 해당/시스템 기본 브라우저를 엽니다.

브라우저가 이미 실행 중인지 감지하고 이를 현재 기본 브라우저로 사용할 수 있는 애플리케이션이나 스크립트가 있습니까?

편집하다

나는 브라우저가 자신의 인스턴스를 감지하는 것을 원하지 않습니다! 브라우저 요청자/스크립트가 열려 있는 브라우저를 감지하고 싶습니다.

  • 예를 들어 Firefox, Google Chrome, Chromium이 있고 PDF 파일의 링크를 클릭하면 Chromium이 열린다고 가정해 보겠습니다. 링크가 Chromium에서 열리길 원합니다.
  • 또 다른 시간에는 Firefox가 열렸습니다. 그런 다음 링크가 Firefox에서 열리길 원합니다.

실제로 저는 이미 열려 있는 브라우저가 시스템 기본 브라우저보다 더 높은 우선순위를 갖기를 원합니다.

답변1

다음 Python 프로그램은 다음을 사용합니다.프수틸모듈을 사용하여 자신에게 속한 프로세스 목록을 가져오고, 알려진 브라우저가 실행 중인지 확인하고, 그렇다면 해당 브라우저를 다시 시작하십시오. 브라우저를 찾을 수 없으면 기본 브라우저가 시작됩니다. 스크립트에서 무슨 일이 일어나고 있는지 명확히 하기 위해 몇 가지 설명을 추가했습니다.

스크립트 자체 외에도 다음 명령을 사용하여 실행 가능하게 만들어야 합니다.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()

관련 정보