如何在Windows上使用Python获取所有显示器的信息?

问题描述 投票:0回答:1

我需要一种方法来获取 Windows 和 Python 中所有已连接显示器的 制造商名称 数据字符串

我的最终目标是一个返回以下内容的函数,例如:

["Lenovo LTN116AT06407", "BenQ G615HDPL"]

我找到了一个软件(madVR),它可以满足我的需要,但我不知道它是如何做的。

python windows
1个回答
2
投票

这可以通过从 python 脚本执行 PowerShell 命令来完成。 要发现计算机上的多显示器配置信息,请使用 powershell Get-WmiObject win32_desktopmonitor 命令。命令输出如下所示:

__GENUS                     : 2
__CLASS                     : Win32_DesktopMonitor
__SUPERCLASS                : CIM_DesktopMonitor
__DYNASTY                   : CIM_ManagedSystemElement
__RELPATH                   : Win32_DesktopMonitor.DeviceID="DesktopMonitor1"
__PROPERTY_COUNT            : 28
__DERIVATION                : {CIM_DesktopMonitor, CIM_Display, CIM_UserDevice,
                               CIM_LogicalDevice...}
__SERVER                    : SQUALL
__NAMESPACE                 : root\cimv2
__PATH                      : \\SQUALL\root\cimv2:Win32_DesktopMonitor.DeviceID
                              ="DesktopMonitor1"
Availability                : 3
Bandwidth                   : 
Caption                     : LG IPS237(Analog)
ConfigManagerErrorCode      : 0
ConfigManagerUserConfig     : False
CreationClassName           : Win32_DesktopMonitor
Description                 : LG IPS237(Analog)
DeviceID                    : DesktopMonitor1
DisplayType                 : 
ErrorCleared                : 
ErrorDescription            : 
InstallDate                 : 
IsLocked                    : 
LastErrorCode               : 
MonitorManufacturer         : LG
MonitorType                 : LG IPS237(Analog)
Name                        : LG IPS237(Analog)
PixelsPerXLogicalInch       : 96
PixelsPerYLogicalInch       : 96
PNPDeviceID                 : DISPLAY\GSM587D\5&2494DFB6&0&UID1048848
PowerManagementCapabilities : 
PowerManagementSupported    : 
ScreenHeight                : 1080
ScreenWidth                 : 1920
Status                      : OK
StatusInfo                  : 
SystemCreationClassName     : Win32_ComputerSystem
SystemName                  : SQUALL

我们需要获取部分Name,因此使用正则表达式。 最终代码为:

import subprocess
import re

proc = subprocess.Popen(['powershell', 'Get-WmiObject win32_desktopmonitor;'], stdout=subprocess.PIPE)
res = proc.communicate()
monitors = re.findall('(?s)\r\nName\s+:\s(.*?)\r\n', res[0].decode("utf-8"))
print(monitors)

结果是:

['LG IPS237(Analog)']
© www.soinside.com 2019 - 2024. All rights reserved.