dpi_test.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import subprocess
  2. import re
  3. def get_gnome_scale() -> float:
  4. """
  5. 优先通过 GNOME gsettings 获取缩放比例
  6. 返回值例如:1.0, 2.0
  7. """
  8. try:
  9. result = subprocess.check_output(
  10. ["gsettings", "get", "org.gnome.desktop.interface", "scaling-factor"],
  11. universal_newlines=True
  12. ).strip()
  13. if result.startswith("uint32"):
  14. val = int(result.split()[-1])
  15. return float(val)
  16. except Exception:
  17. pass
  18. return 1.0
  19. def get_xrandr_scale() -> float:
  20. """
  21. 在 X11 环境下(非 GNOME)通过 xrandr 推算缩放比
  22. 计算逻辑:实际DPI / 标准96dpi
  23. """
  24. try:
  25. output = subprocess.check_output(['xrandr'], universal_newlines=True)
  26. match_res = re.search(r'current (\d+) x (\d+)', output)
  27. match_phys = re.search(r'(\d+)mm x (\d+)mm', output)
  28. if match_res and match_phys:
  29. px_w, px_h = map(int, match_res.groups())
  30. mm_w, mm_h = map(int, match_phys.groups())
  31. dpi_x = px_w / (mm_w / 25.4)
  32. scale = round(dpi_x / 96, 2)
  33. return scale
  34. except Exception:
  35. pass
  36. return 1.0
  37. def get_display_scale() -> float:
  38. """
  39. 自动检测 Ubuntu 桌面显示缩放比例(支持 GNOME、X11)
  40. """
  41. scale = get_gnome_scale()
  42. if scale == 1.0:
  43. scale = get_xrandr_scale()
  44. return scale
  45. if __name__ == "__main__":
  46. scale = get_display_scale()
  47. print(f"检测到系统显示缩放比例:{scale}x")
  48. # export DISPLAY=:0
  49. # Environment=DISPLAY=:0
  50. # Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus