デフォルトのブラウザを開くのではなく、開いているブラウザを自動的に検出します。

デフォルトのブラウザを開くのではなく、開いているブラウザを自動的に検出します。

私のシステムには複数のブラウザ(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()

おすすめ記事