Two examples of how to use Python to obtain information about Windows systems such as CPU, memory, and hard disk

Source: Internet
Author: User
This article mainly introduces two examples of how to use Python to obtain information about the windowns system, such as CPU, memory, and hard disk. the pythonwmi module can be used as a reference. Example 1:

Python uses the WMI module to obtain the hardware information of the windowns system: hard disk partition, usage, memory size, CPU model, current running process, self-starting program and location, and system version.

The code is as follows:


#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Import wmi
Import OS
Import sys
Import platform
Import time

Def sys_version ():
C = wmi. WMI ()
# Obtain the operating system version
For sys in c. Win32_OperatingSystem ():
Print "Version: % s" % sys. Caption. encode ("UTF8"), "Vernum: % s" % sys. BuildNumber
Print sys. OSArchitecture. encode ("UTF8") # whether the system is 32-bit or 64-bit
Print sys. NumberOfProcesses # total number of processes running on the current system

Def cpu_mem ():
C = wmi. WMI ()
# CPU type and memory
For processor in c. Win32_Processor ():
# Print "Processor ID: % s" % processor. DeviceID
Print "Process Name: % s" % processor. Name. strip ()
For Memory in c. Win32_PhysicalMemory ():
Print "Memory Capacity: %. fMB" % (int (Memory. Capacity)/1048576)

Def cpu_use ():
# CPU usage per 5 seconds
C = wmi. WMI ()
While True:
For cpu in c. Win32_Processor ():
Timestamp = time. strftime ('% a, % d % B % Y % H: % M: % s', time. localtime ())
Print '% s | Utilization: % s: % d %' % (timestamp, cpu. DeviceID, cpu. LoadPercentage)
Time. sleep (5)

Def disk ():
C = wmi. WMI ()
# Obtain hard disk partitions
For physical_disk in c. Win32_DiskDrive ():
For partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition "):
For logical_disk in partition. associators ("Win32_LogicalDiskToPartition "):
Print physical_disk.Caption.encode ("UTF8"), partition. Caption. encode ("UTF8"), logical_disk.Caption

# Obtain the disk usage percentage
For disk in c. Win32_LogicalDisk (DriveType = 3 ):
Print disk. Caption, "% 0.2f % free" % (100.0 * long (disk. FreeSpace)/long (disk. Size ))

Def network ():
C = wmi. WMI ()
# Obtain MAC and IP addresses
For interface in c. Win32_NetworkAdapterConfiguration (IPEnabled = 1 ):
Print "MAC: % s" % interface. MACAddress
For ip_address in interface. IPAddress:
Print "ip_add: % s" % ip_address
Print

# Obtain the position of the self-starting Program
For s in c. Win32_StartupCommand ():
Print "[% s] % s <% s>" % (s. location. encode ("UTF8"), s. caption. encode ("UTF8"), s. command. encode ("UTF8 "))


# Obtain the currently running process
For process in c. Win32_Process ():
Print process. ProcessId, process. Name

Def main ():
Sys_version ()
# Cpu_mem ()
# Disk ()
# Network ()
# Cpu_use ()

If _ name _ = '_ main __':
Main ()
Print platform. system ()
Print platform. release ()
Print platform. version ()
Print platform. platform ()
Print platform. machine ()

Example 2:

Because I don't use much, I only get the CPU, memory and hard disk. if you need other resources, please refer to msdn.

The code is as follows:


Import OS
Import win32api
Import win32con
Import wmi
Import time

Def getSysInfo (wmiService = None ):
Result = {}
If wmiService = None:
WmiService = wmi. WMI ()
# Cpu
For cpu in wmiService. Win32_Processor ():
Timestamp = time. strftime ('% a, % d % B % Y % H: % M: % s', time. localtime ())
Result ['cpupercent '] = cpu. loadPercentage
# Memory
Cs = wmiService. Win32_ComputerSystem ()
OS = wmiService. Win32_OperatingSystem ()
Result ['memtotal'] = int (cs [0]. TotalPhysicalMemory)/1024/1024)
Result ['memfree'] = int (OS [0]. FreePhysicalMemory)/1024)
# Disk
Result ['disktotal'] = 0
Result ['diskfree'] = 0
For disk in wmiService. Win32_LogicalDisk (DriveType = 3 ):
Result ['disktotal'] + = int (disk. Size)
Result ['diskfree'] + = int (disk. FreeSpace)
Result ['disktotal'] = int (result ['disktotal']/1024/1024)
Result ['diskfree'] = int (result ['diskfree']/1024/1024)
Return result

If _ name _ = '_ main __':
WmiService = wmi. WMI ()
While True:
Print getSysInfo (wmiService)
Time. sleep (3)

Wmi is obtained by The wmi module. because wmi occupies too many system resources during initialization, if you need to obtain them cyclically, initialize the wmi object outside the loop body and pass it into the function, in this way, the CPU resources will not be too high.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.