Welcome, guest | Sign In | My Account | Store | Cart

Call windows API GetSystemPowerStatus to determine if the AC power is on or off. Great example of calling Windows APIs using Ptyhon.

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import os
import win32con
import sys
import time
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()

while True:
    result = windll.kernel32.GetSystemPowerStatus( byref(powerclass) )

    try:
        state = int(powerclass.ACLineStatus)
    except:
        state = 0 

    if state == 1:
        print 'Power is on...'
    else:
        print 'Power is off...\a'  #\a = bell sounds beep on computer
    
    print 'Sleeping for 5 seconds...'
    time.sleep(5)

During a recent hurricane I wanted to be able to sleep soundly knowing I would be alerted if we lost power. On my laptop, I was able to use python to call windows APIs to let me known when the power failed. I slept rather soundly knowing this was running.

1 comment

aeinein 7 years, 3 months ago  # | flag

I'm trying to use the script, but it keeps giving me an error "ImportError: no module named win32con". I'm using Python 3.4.0