Getting Windows Battery Capacity with Python

I am looking to find out both the current battery capacity and the design capacity.

Until now, I could work using the Win32_Battery () class , which does not provide all the information I need (at least not on my system). For this, I used pure-python wmi library .

On the other hand, I found this that works In Python, how can I determine if a computer is on battery? but, unfortunately, it does not provide any information about this no.

The battery information structure and battery status structure seems ideal for this. Now I know that for this I have to use DeviceIoControl , and I found this C ++ code that explains this a bit.

I would prefer something that just uses ctypes rather than python win32api provided by pywin32 . If you have an idea how to do this in python, please let me know!

Thanks in advance.

+3
source share
2 answers

Tim Golden is an excellent wmi module, I believe it will give you everything you want. You just need to make a few queries to get everything:

import wmi c = wmi.WMI() t = wmi.WMI(moniker = "//./root/wmi") batts1 = c.CIM_Battery(Caption = 'Portable Battery') for i, b in enumerate(batts1): print 'Battery %d Design Capacity: %d mWh' % (i, b.DesignCapacity or 0) batts = t.ExecQuery('Select * from BatteryFullChargedCapacity') for i, b in enumerate(batts): print ('Battery %d Fully Charged Capacity: %d mWh' % (i, b.FullChargedCapacity)) batts = t.ExecQuery('Select * from BatteryStatus where Voltage > 0') for i, b in enumerate(batts): print '\nBattery %d ***************' % i print 'Tag: ' + str(b.Tag) print 'Name: ' + b.InstanceName print 'PowerOnline: ' + str(b.PowerOnline) print 'Discharging: ' + str(b.Discharging) print 'Charging: ' + str(b.Charging) print 'Voltage: ' + str(b.Voltage) print 'DischargeRate: ' + str(b.DischargeRate) print 'ChargeRate: ' + str(b.ChargeRate) print 'RemainingCapacity: ' + str(b.RemainingCapacity) print 'Active: ' + str(b.Active) print 'Critical: ' + str(b.Critical) 

This, of course, is not cross-platform, and it needs a third-party resource, but it works very well.

+8
source

The most reliable way to get this information is to use GetSystemPowerStatus instead of WMI. psutil reveals this information on Linux, Windows, and FreeBSD:

 >>> import psutil >>> >>> def secs2hours(secs): ... mm, ss = divmod(secs, 60) ... hh, mm = divmod(mm, 60) ... return "%d:%02d:%02d" % (hh, mm, ss) ... >>> battery = psutil.sensors_battery() >>> battery sbattery(percent=93, secsleft=16628, power_plugged=False) >>> print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft))) charge = 93%, time left = 4:37:08 

The corresponding commit is here .

+3
source

All Articles