dpi_test.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. print(output)
  27. match_res = re.search(r'current (\d+) x (\d+)', output)
  28. match_phys = re.search(r'(\d+)mm x (\d+)mm', output)
  29. if match_res and match_phys:
  30. px_w, px_h = map(int, match_res.groups())
  31. mm_w, mm_h = map(int, match_phys.groups())
  32. dpi_x = px_w / (mm_w / 25.4)
  33. scale = round(dpi_x / 96, 2)
  34. return scale
  35. except Exception:
  36. pass
  37. return 1.0
  38. def get_display_scale() -> float:
  39. """
  40. 自动检测 Ubuntu 桌面显示缩放比例(支持 GNOME、X11)
  41. """
  42. scale = get_xrandr_scale()
  43. if scale == 1.0:
  44. scale = get_xrandr_scale()
  45. return scale
  46. if __name__ == "__main__":
  47. scale = get_display_scale()
  48. print(f"检测到系统显示缩放比例:{scale}x")
  49. # export DISPLAY=:0
  50. # Environment=DISPLAY=:0
  51. # Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus