3

This question asks how to open an HTML file in the default browser on Mac OS.

There is a useful answer which refers to this infamous bit of Perl:

VERSIONER_PERL_PREFER_32_BIT=true perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'

Here's some working Python code:

import shlex, subprocess

env = {'VERSIONER_PERL_PREFER_32_BIT': 'true'}
raw = """perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'"""
process = subprocess.Popen(shlex.split(raw), env=env, stdout=subprocess.PIPE)
out, err = process.communicate()

default_browser = out.strip()

Is there a more direct way?

Community
  • 1
  • 1
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114

2 Answers2

2

Here's a Python solution using pyobjc:

from Foundation import CFPreferencesCopyAppValue

handlers = CFPreferencesCopyAppValue('LSHandlers', 'com.apple.LaunchServices')

try:
    handler = next(x for x in handlers if x.get('LSHandlerURLScheme') == 'http')
    bundle_identifier = handler.get('LSHandlerRoleAll')
except StopIteration:
    pass

This returns the bundle identifier, which you can use with the -b argument to open.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
1

You can read the "property list" file using plistlib from the standard library:

from pathlib import Path
import plistlib

PREFERENCES = (
    Path.home()
    / "Library"
    / "Preferences"
    / "com.apple.LaunchServices/com.apple.launchservices.secure.plist"
)

NAMES = {
    "com.apple.safari": "Safari",
    "com.google.chrome": "Google Chrome",
    "org.mozilla.firefox": "Firefox",
}

with PREFERENCES.open("rb") as fp:
    data = plistlib.load(fp)

for handler in data["LSHandlers"]:
    if handler.get("LSHandlerURLScheme") == "http":
        role = handler["LSHandlerRoleAll"]
        name = NAMES[role]
        print(name)
Jace Browning
  • 11,699
  • 10
  • 66
  • 90