You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Xlib确定系统的主显示器?

如何用Python Xlib判断X11下的主显示器?

我正在开发一款显示配置应用,希望找到一种通用方法,使用Python Xlib判断哪台显示器被设置为“主显示器”。我目前通过以下代码收集属性:

info = {}
screen = display.Display(':0')
win = screen.screen( screen ).root
res = randr.get_screen_resources( win )
for output in res.outputs:
    props = screen.xrandr_list_output_properties(output)
    for atom in props.atoms:
        atom_name = screen.get_atom_name(atom)
        atom_info = screen.xrandr_get_output_property( output, atom, 0, 0, 1000).value[0]
        if isinstance( atom_info, int ):
            atom_info = screen.get_atom_name( atom_info )
        info[atom_name] = atom_info

我在两台Arch Linux KDE设备上测试,在笔记本电脑上发现了名为“_KDE_SCREEN_INDEX”的原子,似乎符合需求,但它在其他桌面环境甚至另一台KDE设备上都不生效。我想了解xrandr识别主显示器的标志,从而通过Xlib实现该功能,同时希望避免在应用中调用外部xrandr命令。


解决方案:使用XRandR标准属性判断主显示器

不要依赖桌面环境的私有原子(如_KDE_SCREEN_INDEX),这类原子是特定桌面环境专属的,不具备通用性。XRandR扩展本身定义了标准的主显示器标记,所有符合X11规范的桌面环境都会遵循这一标准。

核心思路

通过Xlib的XRandR扩展获取每个输出的XRROutputInfo结构体,其中的primary布尔字段直接标记了该输出是否为主显示器,这是最通用的判断方式。

实现代码

from Xlib import display
from Xlib.ext import randr

def get_primary_display():
    # 连接到本地X显示
    d = display.Display(':0')
    root = d.screen().root
    # 获取屏幕资源
    res = randr.get_screen_resources(root)
    
    # 遍历所有输出设备
    for output in res.outputs:
        # 获取输出设备的详细信息
        output_info = d.xrandr_get_output_info(output, res.config_timestamp)
        # 检查是否为主显示器
        if output_info.primary:
            # 获取输出设备的名称(如eDP-1、HDMI-1)
            output_name = d.get_atom_name(output_info.name)
            return output_name, output_info
    
    # 理论上X11环境至少有一个主显示器,此处为容错处理
    return None, None

# 调用示例
primary_name, primary_info = get_primary_display()
if primary_name:
    print(f"主显示器: {primary_name}")
    # 提取主显示器的当前分辨率(取第一个有效模式)
    current_mode = primary_info.modes[0]
    print(f"当前分辨率: {current_mode.width}x{current_mode.height}")
else:
    print("未找到主显示器")

代码说明

  • xrandr_get_output_info返回的XRROutputInfo对象包含了输出设备的所有关键信息,其中primary字段是XRandR标准定义的主显示器标记。
  • 该方法不依赖任何桌面环境的私有API,适用于GNOME、KDE、Xfce、i3等所有支持XRandR的X11桌面环境。
  • 可通过output_info的其他字段(如modes、crtc)进一步获取主显示器的分辨率、位置、刷新率等信息。

内容的提问来源于stack exchange,提问作者Erik Beebe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:04:57