如果您不希望这样做,则win32api
可以使用内置ctypes
模块。我通常在不使用cpython的情况下运行cpythonwin32api
,因此我很喜欢这些解决方案。
GetSystemPowerStatus()
因为您必须定义SYstem_POWER_STATUS
结构,所以还需要做更多的工作,但还不错。
# Get power status of the system using ctypes to call GetSystemPowerStatus
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
在打印此内容的系统上(基本上是指“台式机,已插入”):
ACLineStatus 1
BatteryFlag -128
BatteryLifePercent -1
BatteryLifeTime 4294967295
BatteryFullLifeTime 4294967295