12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import subprocess
- import re
- def get_gnome_scale() -> float:
- """
- 优先通过 GNOME gsettings 获取缩放比例
- 返回值例如:1.0, 2.0
- """
- try:
- result = subprocess.check_output(
- ["gsettings", "get", "org.gnome.desktop.interface", "scaling-factor"],
- universal_newlines=True
- ).strip()
- if result.startswith("uint32"):
- val = int(result.split()[-1])
- return float(val)
- except Exception:
- pass
- return 1.0
- def get_xrandr_scale() -> float:
- """
- 在 X11 环境下(非 GNOME)通过 xrandr 推算缩放比
- 计算逻辑:实际DPI / 标准96dpi
- """
- try:
- output = subprocess.check_output(['xrandr'], universal_newlines=True)
- print(output)
- match_res = re.search(r'current (\d+) x (\d+)', output)
- match_phys = re.search(r'(\d+)mm x (\d+)mm', output)
- if match_res and match_phys:
- px_w, px_h = map(int, match_res.groups())
- mm_w, mm_h = map(int, match_phys.groups())
- dpi_x = px_w / (mm_w / 25.4)
- scale = round(dpi_x / 96, 2)
- return scale
- except Exception:
- pass
- return 1.0
- def get_display_scale() -> float:
- """
- 自动检测 Ubuntu 桌面显示缩放比例(支持 GNOME、X11)
- """
- scale = get_xrandr_scale()
- if scale == 1.0:
- scale = get_xrandr_scale()
- return scale
- if __name__ == "__main__":
- scale = get_display_scale()
- print(f"检测到系统显示缩放比例:{scale}x")
- # export DISPLAY=:0
- # Environment=DISPLAY=:0
- # Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
|