ryan27968
ryan27968

Reputation: 477

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.

Upvotes: 3

Views: 2434

Answers (2)

python必须死
python必须死

Reputation: 1089

```

import subprocess

wmic =  subprocess.getoutput("wmic path win32_battery get EstimatedChargeRemaining")
print(wmic)

```

output:

EstimatedChargeRemaining  

96               

Upvotes: 0

falsetru
falsetru

Reputation: 369444

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

Upvotes: 8

Related Questions