对于windows系统的电脑使用Python可以对其当前的窗口进行宏观的查询等操作
派生博客1:python对pc的窗口进行操作(windows)
派生博客2python获取当前pc的分辨率(windows)
派生博客3使用uiautomation模块来对基于windows系统的pc中的前端界面进行自动化测试(查找控件,点击控件等)
相关接口说明
根据当前传进函数的窗口句柄获取此句柄对应的窗口信息(标题,class等)
# 直接获取当前pc最上面窗口的句柄
page_hwnd = win32gui.GetForegroundWindow()
# 根据窗口句柄获取此句柄对应的窗口的标题
title = win32gui.GetWindowText(hWnd)
# 根据窗口句柄获取此句柄对应的窗口的class名
title = win32gui.GetWindowText(hWnd)
# 根据窗口句柄获取窗口的坐标数值 得到的返回值为元组类型如(12,15,214,166),左上右下
left, top, right, down = win32gui.GetWindowRect(page_hwnd)# 获取子窗口的父窗口句柄
parent_handle = win32gui.GetParent(child_handle)
根据窗口的句柄值判断当前窗口是否是实体窗口(是的话返回1)
非显性窗口指的不是最小化隐藏的窗口,只要需要知道我们需要操作的窗口一般都是显性窗口就行了
import win32gui
# 根据窗口的句柄值判断当前窗口是否是实体窗口(个人认为显示窗口指的是实打实用户可见的窗口,一个窗口如果是显式窗口的话就算当前窗口在任务栏最小化也不会改变其窗口的显式特性)
# 非显性窗口指的不是最小化隐藏的窗口
print(win32gui.IsWindowVisible(page_hwnd))
print(win32gui.IsWindowVisible(66594))
# 返回值0/1
确定是否为鼠标和键盘输入启用了指定的窗口。窗口可用。
# 确定是否为鼠标和键盘输入启用了指定的窗口。窗口可用。
# 返回值:如果启用该窗口,则返回值不为零。如果窗口未启用,返回值为零。
# 备注:子窗口只有在启用和可见时才接收输入。
win32gui.IsWindowEnabled(hwnd)
根据进程id判断进程对应的名字
# python -m pip install psutil
import psutil
# 根据进程id判断进程对应的名字
psutil.Process(pid).name()# python -m pip install psutil
import psutil
import win32gui
import win32process
def activeWindowName():# 获取最上层窗口的句柄hwnd = win32gui.GetForegroundWindow()# 根据窗口句柄获取窗口对应的线程id和进程idtid, pid = win32process.GetWindowThreadProcessId(hwnd)# 根据进程id判断进程对应的名字return psutil.Process(pid).name()print(activeWindowName())
# pycharm64.exe
根据应用的窗口句柄获取对应应用的进程id
import win32process
# 根据应用的窗口句柄获取对应应用的线程id(我一般用这个用的很少)和进程id
# thread_id , process_id = win32process.GetWindowThreadProcessId(hwnd)
枚举当前windows电脑的所有窗口
win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
样例如下
import win32gui# 提前定义一个列表以便传递到win32gui.EnumWindows中保存数据
save_all_window_hwnd_list = []# win32gui.EnumWindows()第一个参数是一个函数地址,第二个参数一般是个列表或者字典这种科比那容器,以便每次往里面添加数据并保存
win32gui.EnumWindows(lambda hWnd, save_all_window_hwnd_list: save_all_window_hwnd_list.append(hWnd), save_all_window_hwnd_list)
# 枚举当前所有窗口的句柄,此接口的第一个参数传递一个有两个参数的函数的地址,第二个参数一般可以传递一个列表字典等容器
# 在每次枚举的时候会调用第一个参数的函数,然后将每次枚举出来的窗口的句柄传递给调用win32gui.EnumWindows函数时传递的第一个参数也就是那个函数,将调用win32gui.EnumWindows函数时传递的第二个参数也传递给那个函数# 电脑此前所有窗口的窗口句柄的列表
print(save_all_window_hwnd_list)# 便利窗口句柄列表,并且打印每个窗口句柄所对应的窗口标题
for one_hwnd in save_all_window_hwnd_list:print(win32gui.GetWindowText(one_hwnd))
通过应用的窗口句柄获取窗口从属的进程名有时候是当前窗口所在应用有时候是窗口从属应用的父应用
# python -m pip install wmi
import wmi
def get_app_name(hwnd):"""通过应用的窗口句柄获取窗口从属的进程名有时候是当前窗口所在应用有时候是窗口从属应用的父应用Get application filename given hwnd."""c = wmi.WMI()name = None_, pid = win32process.GetWindowThreadProcessId(hwnd)for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):name = p.Namebreakreturn name
通过给定的应用窗口句柄获取此应用的启动文件路径
# python -m pip install wmi
import wmi
def get_app_path(app_page_hwnd):"""通过给定的应用窗口句柄获取此应用的启动文件路径Get application path given hwnd."""c = wmi.WMI()path = None_, pid = win32process.GetWindowThreadProcessId(app_page_hwnd)for p in c.query('SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = %s' % str(pid)):path = p.ExecutablePathbreakreturn pathprint(get_app_path("本机电脑当前打开的pycharm页面hwnd"))# D:\Program Files\JetBrains\PyCharm Community Edition 2020.2.1\bin\pycharm64.exe
wmi模块拓展接口
查询当前运行的程序信息(可以指定具体进程名)
# 查询当前运行的程序信息(可以指定具体进程名)
# python -m pip install wmi
import wmi
c = wmi.WMI()
for process in c.Win32_Process():print(str(process))print("========================")for process in c.Win32_Process(name="calc.exe"):print(str(process))
用于获取CPU处理器信息对象,并存以列表形式
import wmiw = wmi.WMI()
cpu_list = w.Win32_Processor()for cpu in cpu_list:print(cpu)'''
instance of Win32_Processor
{AddressWidth = 64;Architecture = 9;Availability = 3;Caption = "Intel64 Family 6 Model 69 Stepping 1";CpuStatus = 1;CreationClassName = "Win32_Processor";CurrentClockSpeed = 1587;CurrentVoltage = 7;DataWidth = 64;Description = "Intel64 Family 6 Model 69 Stepping 1";DeviceID = "CPU0";ExtClock = 100;Family = 205;L2CacheSize = 256;L3CacheSize = 3072;L3CacheSpeed = 0;Level = 6;LoadPercentage = 32;Manufacturer = "GenuineIntel";MaxClockSpeed = 2301;Name = "Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz";NumberOfCores = 2;NumberOfLogicalProcessors = 4;PowerManagementSupported = FALSE;ProcessorId = "BFEBFBFF00040651";ProcessorType = 3;Revision = 17665;Role = "CPU";SocketDesignation = "CPU Socket - U3E1";Status = "OK";StatusInfo = 3;SystemCreationClassName = "Win32_ComputerSystem";SystemName = "QH-20181120YSCF";UpgradeMethod = 33;Version = "";
};
'''
获取当前pc的cpu的型号和cpu的核心数
# 获取当前pc的cpu的型号和cpu的核心数
# cpu.Name 是cpu的型号
# cpu.NumberOfCores 是cpu的核心数# python -m pip install wmi
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
for cpu in cpu_list:print("cpu核心数",cpu.NumberOfCores)print("cpu型号",cpu.Name)# cpu核心数 4
# cpu型号 Intel(R) Core(TM) i5-6300HQ CPU @ 2.30GHz
统计cpu个数
# 统计cpu个数
# python -m pip install wmi
import wmi
w = wmi.WMI()
cpu_list = w.Win32_Processor()
print(len(cpu_list))# 1
获取一些电脑信息1
import wmiw = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]print(obj)'''
instance of Win32_ComputerSystem
{AdminPasswordStatus = 3;AutomaticManagedPagefile = TRUE;AutomaticResetBootOption = TRUE;AutomaticResetCapability = TRUE;BootOptionOnLimit = 3;BootOptionOnWatchDog = 3;BootROMSupported = TRUE;BootupState = "Normal boot";Caption = "QH-20181120YSCF";ChassisBootupState = 3;CreationClassName = "Win32_ComputerSystem";CurrentTimeZone = 480;Description = "AT/AT COMPATIBLE";DNSHostName = "QH-20181120YSCF";Domain = "WORKGROUP";DomainRole = 0;EnableDaylightSavingsTime = TRUE;FrontPanelResetStatus = 3;InfraredSupported = FALSE;KeyboardPasswordStatus = 3;Manufacturer = "Dell Inc.";Model = "Inspiron 5439";Name = "QH-20181120YSCF";NetworkServerModeEnabled = TRUE;NumberOfLogicalProcessors = 4;NumberOfProcessors = 1;OEMStringArray = {"Dell System", "1[0638]", "3[1.3]", "4[0001]", "6[D0, D4, D8, DA, DE]", "10[A04]", "8[]", "9[]", "10[XXX]", "13[PP36S]", "14[3]", "15[9]", "16[]"};PartOfDomain = FALSE;PauseAfterReset = "3932100000";PCSystemType = 2;PowerOnPasswordStatus = 3;PowerState = 0;PowerSupplyState = 3;PrimaryOwnerName = "PC";ResetCapability = 1;ResetCount = -1;ResetLimit = -1;Roles = {"LM_Workstation", "LM_Server", "NT", "Potential_Browser"};Status = "OK";SystemType = "x64-based PC";ThermalState = 3;TotalPhysicalMemory = "4198264832";UserName = "QH-20181120YSCF\\Administrator";WakeUpType = 6;Workgroup = "WORKGROUP";
};
'''
查询当前机器型号和制造商
# 查询机器型号和制造商
# python -m pip install wmi
import wmi
w = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]print("机器型号",obj.model)
print("制造商",obj.Manufacturer)# 机器型号 Inspiron 7559
# 制造商 Dell Inc.
获取一些电脑信息2
import wmiw = wmi.WMI()
obj = w.Win32_ComputerSystem()[0]
print(obj)'''
instance of Win32_OperatingSystem
{BootDevice = "\\Device\\HarddiskVolume1";BuildNumber = "7601";BuildType = "Multiprocessor Free";Caption = "Microsoft Windows 7 旗舰版 ";CodeSet = "936";CountryCode = "86";CreationClassName = "Win32_OperatingSystem";CSCreationClassName = "Win32_ComputerSystem";CSDVersion = "Service Pack 1";CSName = "QH-20181120YSCF";CurrentTimeZone = 480;DataExecutionPrevention_32BitApplications = TRUE;DataExecutionPrevention_Available = TRUE;DataExecutionPrevention_Drivers = TRUE;DataExecutionPrevention_SupportPolicy = 2;Debug = FALSE;Description = "";Distributed = FALSE;EncryptionLevel = 256;ForegroundApplicationBoost = 2;FreePhysicalMemory = "431452";FreeSpaceInPagingFiles = "2710880";FreeVirtualMemory = "2671984";InstallDate = "20181120154345.000000+480";LastBootUpTime = "20190221005145.164410+480";LocalDateTime = "20190309002538.760000+480";Locale = "0804";Manufacturer = "Microsoft Corporation";MaxNumberOfProcesses = 4294967295;MaxProcessMemorySize = "8589934464";MUILanguages = {"zh-CN"};Name = "Microsoft Windows 7 旗舰版 |C:\\Windows|\\Device\\Harddisk0\\Partition1";NumberOfLicensedUsers = 0;NumberOfProcesses = 115;NumberOfUsers = 1;OperatingSystemSKU = 1;Organization = "Microsoft";OSArchitecture = "64-bit";OSLanguage = 2052;OSProductSuite = 256;OSType = 18;Primary = TRUE;ProductType = 1;RegisteredUser = "PC";SerialNumber = "00426-OEM-8992662-00006";ServicePackMajorVersion = 1;ServicePackMinorVersion = 0;SizeStoredInPagingFiles = "6119656";Status = "OK";SuiteMask = 272;SystemDevice = "\\Device\\HarddiskVolume1";SystemDirectory = "C:\\Windows\\system32";SystemDrive = "C:";TotalVirtualMemorySize = "10217684";TotalVisibleMemorySize = "4099868";Version = "6.1.7601";WindowsDirectory = "C:\\Windows";
};
'''
获取pc的sn号
import wmiw = wmi.WMI()
obj = w.Win32_OperatingSystem()[0]
print("sn",obj.SerialNumber)
# sn 00426-OEM-8992662-00006
获取物理磁盘信息
import wmi
w = wmi.WMI()
disk = w.Win32_DiskDrive()[0]
print(disk)'''
instance of Win32_DiskDrive
{BytesPerSector = 512;Capabilities = {3, 4, 10};CapabilityDescriptions = {"Random Access", "Supports Writing", "SMART Notification"};Caption = "ST500LT0 12-1DG142 SCSI Disk Device";ConfigManagerErrorCode = 0;ConfigManagerUserConfig = FALSE;CreationClassName = "Win32_DiskDrive";Description = "磁盘驱动器";DeviceID = "\\\\.\\PHYSICALDRIVE0";FirmwareRevision = "0001";Index = 0;InterfaceType = "IDE";Manufacturer = "(标准磁盘驱动器)";MediaLoaded = TRUE;MediaType = "Fixed hard disk media";Model = "ST500LT0 12-1DG142 SCSI Disk Device";Name = "\\\\.\\PHYSICALDRIVE0";Partitions = 4;PNPDeviceID = "SCSI\\DISK&VEN_ST500LT0&PROD_12-1DG142\\4&30B6A92E&0&010000";SCSIBus = 1;SCSILogicalUnit = 0;SCSIPort = 0;SCSITargetId = 0;SectorsPerTrack = 63;SerialNumber = " W3P2DXE1";Signature = 2837888961;Size = "500105249280";Status = "OK";SystemCreationClassName = "Win32_ComputerSystem";SystemName = "QH-20181120YSCF";TotalCylinders = "60801";TotalHeads = 255;TotalSectors = "976768065";TotalTracks = "15504255";TracksPerCylinder = 255;
};
'''
获取硬盘sn 、硬盘大小 、型号制造商 、硬盘型号
import wmi
w = wmi.WMI()
disk = w.Win32_DiskDrive()[0]print("硬盘制造商Manufacturer",disk.Manufacturer)
print("硬盘型号", disk.Model)
print("硬盘sn", disk.SerialNumber)
print("硬盘大小", int(disk.Size) / (1024 * 1024 * 1024))'''
硬盘制造商Manufacturer (标准磁盘驱动器)
硬盘型号 ST500LT0 12-1DG142 SCSI Disk Device
硬盘sn W3P2DXE1
硬盘大小 465.7593083381653
'''
用于获取网络接口信息对象,并存以列表形式
Win32_NetworkAdapterConfiguration() 方法
获取所有网卡信息
w = wmi.WMI()
data = {}
count = 0
for nic in w.Win32_NetworkAdapterConfiguration():if nic.MACAddress is not None:count+=1item_data = {}item_data['macaddress'] = nic.MACAddressitem_data['model'] = nic.Captionitem_data['name'] = nic.Indexif nic.IPAddress is not None:item_data['ipaddress'] = nic.IPAddress[0]item_data['netmask'] = nic.IPSubnetelse:item_data['ipaddress'] = ""item_data['netmask'] = ""data["nic%s" %count] = item_dataprint(data)'''
{'nic1': {'macaddress': 'FE:F8:AE:B0:93:4D', 'model': '[00000012] Microsoft Virtual WiFi Miniport Adapter', 'name': 12, 'ipaddress': '', 'netmask': ''}, 'nic2': {'macaddress': 'E0:DB:55:EC:EF:DC', 'model': '[00000013] Realtek PCIe GBE Family Controller', 'name': 13, 'ipaddress': '', 'netmask': ''}, 'nic3': {'macaddress': 'FC:F8:AE:B0:93:51', 'model': '[00000016] Bluetooth 设备(个人区域网)', 'name': 16, 'ipaddress': '', 'netmask': ''}, 'nic4': {'macaddress': '00:50:56:C0:00:01', 'model': '[00000018] VMware Virtual Ethernet Adapter for VMnet1', 'name': 18, 'ipaddress': '192.168.234.1', 'netmask': ('255.255.255.0', '64')}, 'nic5': {'macaddress': 'FC:F8:AE:B0:93:4D', 'model': '[00000019] Intel(R) Wireless-N 7260', 'name': 19, 'ipaddress': 'x.x.x.x', 'netmask': ('255.255.255.0', '64')}, 'nic6': {'macaddress': '00:50:56:C0:00:08', 'model': '[00000020] VMware Virtual Ethernet Adapter for VMnet8','name': 20,'ipaddress': 'x.x.x.x', 'netmask': ('255.255.0.0', '64')}, 'nic7': {'macaddress': 'FE:F8:AE:B0:93:4E', 'model': '[00000023] Microsoft Virtual WiFi Miniport Adapter', 'name': 23, 'ipaddress': '', 'netmask': ''}}
'''