在Python中确定Mac默认浏览器
这个问题是在问如何在Mac OS上用默认浏览器打开一个HTML文件。
有一个很有用的回答,提到了这段臭名昭著的Perl代码:
VERSIONER_PERL_PREFER_32_BIT=true perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'
这里有一些可以用的Python代码:
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()
有没有更直接的方法呢?
2 个回答
1
你可以使用标准库里的 plistlib 来读取“属性列表”文件:
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)
2
这里有一个使用pyobjc的Python解决方案:
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
这个代码会返回一个包标识符,你可以用这个标识符配合-b
参数来使用open
命令。