Search code examples
pythonclasspython-2.7wmibatterylevel

Get battery status using wmi in python?


I know how to use wmi, I have used it before, however, the wmi class it seems i need to call is GetSystemPowerStatus. but i am having trouble finding and documentation on it. to be able to access it, i need to know the namespace, and the format of the data inside the class. could someone help me? Also some sample code would be nice.


Solution

  • Using ctypes, you can call win32 api:

    from ctypes import *
    
    class PowerClass(Structure):
        _fields_ = [('ACLineStatus', c_byte),
                ('BatteryFlag', c_byte),
                ('BatteryLifePercent', c_byte),
                ('Reserved1',c_byte),
                ('BatteryLifeTime',c_ulong),
                ('BatteryFullLifeTime',c_ulong)]    
    
    powerclass = PowerClass()
    result = windll.kernel32.GetSystemPowerStatus(byref(powerclass))
    print(powerclass.BatteryLifePercent)
    

    Above code comes from here.


    Using Win32_Battery class (You need to install pywin32):

    from win32com.client import GetObject
    
    WMI = GetObject('winmgmts:')
    for battery in WMI.InstancesOf('Win32_Battery'):
        print(battery.EstimatedChargeRemaining)
    

    Alternative that use wmi package:

    import wmi
    
    w = wmi.WMI()
    for battery in w.query('select * from Win32_Battery'):
        print battery.EstimatedChargeRemaining