Skip to content

Instantly share code, notes, and snippets.

@lesthack
Forked from wangqr/battery.py
Created September 23, 2019 17:22

Revisions

  1. @wangqr wangqr created this gist Sep 17, 2017.
    30 changes: 30 additions & 0 deletions battery.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    #! /usr/bin/env python3
    # -*- coding: utf-8 -*-

    import ctypes
    from ctypes import wintypes

    class SYSTEM_POWER_STATUS(ctypes.Structure):
    _fields_ = [
    ('ACLineStatus', wintypes.BYTE),
    ('BatteryFlag', wintypes.BYTE),
    ('BatteryLifePercent', wintypes.BYTE),
    ('Reserved1', wintypes.BYTE),
    ('BatteryLifeTime', wintypes.DWORD),
    ('BatteryFullLifeTime', wintypes.DWORD),
    ]

    SYSTEM_POWER_STATUS_P = ctypes.POINTER(SYSTEM_POWER_STATUS)

    GetSystemPowerStatus = ctypes.windll.kernel32.GetSystemPowerStatus
    GetSystemPowerStatus.argtypes = [SYSTEM_POWER_STATUS_P]
    GetSystemPowerStatus.restype = wintypes.BOOL

    status = SYSTEM_POWER_STATUS()
    if not GetSystemPowerStatus(ctypes.pointer(status)):
    raise ctypes.WinError()
    print('ACLineStatus', status.ACLineStatus)
    print('BatteryFlag', status.BatteryFlag)
    print('BatteryLifePercent', status.BatteryLifePercent)
    print('BatteryLifeTime', status.BatteryLifeTime)
    print('BatteryFullLifeTime', status.BatteryFullLifeTime)