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

如何在macOS系统下通过Python获取显示器物理尺寸?

在macOS通过Python获取指定显示器物理尺寸的方案

方法1:利用AppKit的NSScreen深层属性

你之前查阅NSScreen文档时可能没注意到,它的deviceDescription字典里包含NSDevicePhysicalSize键,对应的值就是显示器的物理尺寸(单位:毫米),可通过PyObjC直接调用:

import AppKit

def get_display_physical_size():
    screens = AppKit.NSScreen.screens()
    for idx, screen in enumerate(screens):
        desc = screen.deviceDescription()
        physical_size = desc[AppKit.NSDevicePhysicalSize]
        # NSSize对象的width和height属性对应宽高(毫米)
        print(f"显示器{idx+1}: 宽{physical_size.width:.1f}mm,高{physical_size.height:.1f}mm")

get_display_physical_size()

方法2:解析system_profiler命令输出

macOS自带的system_profiler工具可输出显示器详细信息,包括物理尺寸。通过Python的subprocess调用该命令并解析文本:

import subprocess
import re

def get_display_physical_size_via_system_profiler():
    # 执行命令获取显示器信息
    result = subprocess.run(
        ["system_profiler", "SPDisplaysDataType"],
        capture_output=True,
        text=True
    )
    output = result.stdout
    # 匹配物理尺寸的正则,例如"59.7 cm x 33.6 cm"格式
    pattern = r"Resolution:.*\((\d+\.\d+) cm x (\d+\.\d+) cm\)"
    matches = re.findall(pattern, output)
    for idx, (width_cm, height_cm) in enumerate(matches):
        width_mm = float(width_cm) * 10
        height_mm = float(height_cm) * 10
        print(f"显示器{idx+1}: 宽{width_mm:.1f}mm,高{height_mm:.1f}mm")

get_display_physical_size_via_system_profiler()

方法3:读取EDID信息(IOKit框架)

显示器的EDID数据包含物理尺寸信息,通过PyObjC调用IOKit框架可读取并解析:

import objc
from Foundation import NSData

# 加载IOKit框架
IOKit = objc.loadBundle(
    'IOKit',
    bundle_path='/System/Library/Frameworks/IOKit.framework',
    module_globals=globals()
)

def get_display_physical_size_via_edid():
    # 获取显示器服务迭代器
    iterator = IOKit.IOServiceMatching("IODisplayConnect")
    err, iterator = IOKit.IOServiceGetMatchingServices(0, iterator, None)
    services = []
    while True:
        service = IOKit.IOIteratorNext(iterator)
        if service == 0:
            break
        services.append(service)
    IOKit.IOObjectRelease(iterator)

    for idx, service in enumerate(services):
        # 获取EDID数据
        edid_data = IOKit.IORegistryEntryCreateCFProperty(
            service,
            "IODisplayEDID",
            None,
            0
        )
        if edid_data:
            edid_bytes = bytes(edid_data)
            # EDID第15、16字节分别为宽、高(单位:0.1厘米)
            width_01cm = edid_bytes[15]
            height_01cm = edid_bytes[16]
            width_mm = width_01cm * 1
            height_mm = height_01cm * 1
            print(f"显示器{idx+1}: 宽{width_mm:.1f}mm,高{height_mm:.1f}mm")
        IOKit.IOObjectRelease(service)

get_display_physical_size_via_edid()

注意:EDID的物理尺寸数据可能在部分显示器上存在误差,优先推荐方法1或2。

内容的提问来源于stack exchange,提问作者Jason C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:42:50